<script lang="ts">
    import { onMount } from "svelte";
    import { supabase } from "$lib/supabaseClient";
    import Pagination from "$lib/Pagination.svelte";

    type Project = {
        id: string;
        issue_id: string;
        project_number: string;
        add_to_po: boolean;
        input_by: string;
        project_due_date: string;
        picture_link: string;
        villa_data?: string; // Optional, if not always present
    };

    type insertProject = {
        issue_id: string;
        input_by: string;
        project_start_date?: string;
        project_due_date: string;
        picture_link: string;
        updated_at?: string; // Optional, if not always present
        updated_by?: string; // Optional, if not always present
    };

    type Projects = {
        id: string;
        priority: string;
        add_to_po: boolean;
        description_of_the_issue: string;
        picture_link: string;
        need_approval: boolean;
        area_of_villa: string;
        input_by: string;
        project_name: string;
        issue_number: string;
        issue_id: string;
        report_date: string;
        project_start_date?: string; 
        project_due_date: string;
        project_number?: string; // Optional, if not always present
        assigned_name?: string; // Optional, if not always present
        updated_at?: string; // Optional, if not always present
        updated_name?: string; // Optional, if not always present
    };

    let allRows: Projects[] = [];

    type columns = {
        key: string;
        title: string;
    };

    const columns: columns[] = [
        { key: "description_of_the_issue", title: "Issue Description" },
        { key: "project_name", title: "Project Name" },
        { key: "project_number", title: "Project Number" },
        { key: "priority", title: "Priority" },
        { key: "add_to_po", title: "Add to PO" },
        { key: "picture_link", title: "Picture Link" },
        { key: "area_of_villa", title: "Area of Villa" },
        { key: "project_status", title: "Status" },
        { key: "project_comment", title: "Comment" },
        { key: "input_name", title: "Input By" },
        { key: "issue_number", title: "Issue Number" },
        { key: "villa_name", title: "Villa Name" },
        { key: "report_date", title: "Report Date" },
        { key: "project_due_date", title: "Project Due Date" },
        { key: "need_approval", title: "Need Approval" },
        { key: "assigned_name", title: "Assign To" },
        { key: "created_at", title: "Created At" },
        { key: "updated_at", title: "Updated At" },
        { key: "updated_name", title: "Updated By" },
        { key: "actions", title: "Actions" },
    ];

    let selectedFile: File | null = null;
    let imagePreviewUrl: string | null = null;
    let showPoModal = false;
    let newPurchaseOrder: Record<string, any> = {};
    let poItems: any[] = [];
    let addToPoInProgress: Set<string> = new Set();
    let employees: any[] = [];
    let villas: any[] = [];
    let showEditModal = false;

    let editForm = {
        po_number: "",
        issue_name: "",
        villa_id: "",
        po_status: "",
        prepared: null,
        approved: null,
        acknowledged: null,
        completed: null,
        received: null,
        po_remark: ""
    };
    let showProjectEditModal = false;
    let projectEditForm = {
        project_number: "",
        issue_desc: "",
        project_name: "",
        project_start_date:"",
        project_due_date:"",
        project_status: "On Progress",
        project_comment: "",
        picture_link: "",
        assigned_to: "",
        updated_at: "",
        updated_by: ""
    };

    function openProjectEditModal(row) {
        projectEditForm = {
            project_number: row.project_number || "",
            issue_desc: row.issue_name || "",
            project_name: row.project_name || "",
            project_start_date: row.project_start_date || "",
            project_due_date: row.project_due_date || "",
            project_status: row.project_status || "On Progress",
            project_comment: row.project_comment || "",
            picture_link: row.picture_link || "",
            assigned_to: row.assigned_to || "",
            updated_at: new Date().toISOString(),
            updated_by: row.updated_by || ""
        };
        showProjectEditModal = true;
    }
    function openEditModal(row) {
        selectedPO = row;

        editForm = {
            po_number: row.purchase_order_number || "",
            issue_name: row.issue_name || "",
            villa_id: row.villa_id || "",
            po_status: row.po_status || "",
            prepared: row.prepared,
            approved: row.approved,
            acknowledged: row.acknowledged,
            completed: row.completed,
            received: row.received,
            po_remark: row.po_remark || ""
        };

        showEditModal = true;
    }


    async function fetchVillas() {
        const { data, error } = await supabase
            .from("vb_villas")
            .select("villa_name")
            .eq("villa_status", "Active");
        if (error) console.error(error);
        else villas = data;
    }

    async function fetchActiveEmployees() {
        const { data, error } = await supabase
            .from("vb_employee")
            .select("id, employee_name, employee_status")
            .eq("employee_status", "Active")
            .order("employee_name", { ascending: true });

        if (error) {
            console.error("Error fetching employees:", error);
        } else {
            employees = data;
        }
    }

    async function fetchPoItems() {
        const { data, error } = await supabase.from("vb_po_item").select("*");
        if (error) console.error("Error fetching PO items", error);
        else poItems = data;
    }

    async function saveEdit() {
        const { error } = await supabase
            .from("vb_purchase_orders")
            .update({
            prepared: editForm.prepared,
            approved: editForm.approved,
            acknowledged: editForm.acknowledged,
            completed: editForm.completed,
            received: editForm.received,
            po_remark: editForm.po_remark
            })
            .eq("id", selectedPO.id);

        if (error) {
            console.error("Error saving edit:", error);
            alert("Failed to save changes.");
            return;
        }

        showEditModal = false;
        await fetchPurchaseOrder();
    }
    function handleFileChange(event: Event) {
        const input = event.target as HTMLInputElement;
        if (input.files && input.files.length > 0) {
            selectedFile = input.files[0];
            imagePreviewUrl = URL.createObjectURL(selectedFile);
        }
    }

    let currentPage = 1;
    let rowsPerPage = 10;
    $: totalPages = Math.ceil(allRows.length / rowsPerPage);
    $: paginatedRows = allRows.slice(
        (currentPage - 1) * rowsPerPage,
        currentPage * rowsPerPage,
    );

    function goToPage(page: number) {
        if (page >= 1 && page <= totalPages) currentPage = page;
    }

    async function fetchProjects(
        filter: string | null = null,
        searchTerm: string | null = null,
        sortBy: string | null = null,
        sortOrder: "asc" | "desc" = "asc",
        offset: number = 0,
        limit: number = 10,
    ) {
        let query = supabase
            .from("vb_projects_data")
            .select("*", { count: "exact" })
            .order(sortBy || "created_at", { ascending: sortOrder === "asc" })
            .range(offset, offset + limit - 1);
        // Apply filter if provided
        if (filter) {
            query = query.eq("villa_name", filter);
        }

        // Fetch projects
        const { data, error } = await query;
        if (error) {
            console.error("Error fetching projects:", error);
            return;
        }

        // ambil issue_id dari projects kemudian ambil data issue yang sesuai
        const issueIds = data?.map((project: Project) => project.issue_id);
        const { data: issueData, error: issueError } = await supabase
            .from("vb_issues")
            .select("*")
            .in("id", issueIds || [])
            .order("id", { ascending: false });

        // gabungkan data projects dengan data issues
        if (!data || !issueData) {
            console.error("Error fetching projects or issues:", error);
            return;
        }

        allRows = []; // Reset allRows before populating

        // Set allRows to the combined data
        allRows = data.map((project: Project) => {
            const issue = issueData.find(
                (issue) => issue.id === project.issue_id,
            );
            return {
                ...project,
                id: project.id,
                description_of_the_issue: issue ? issue.description_of_the_issue : "Unknown",
                priority: issue ? issue.priority : "Unknown",
                add_to_po: project.add_to_po,
                picture_link: project.picture_link,
                need_approval: issue ? issue.need_approval : false,
                area_of_villa: issue ? issue.area_of_villa : "Unknown",
                input_by: project.input_by,
                issue_number: issue ? issue.issue_number : "Unknown",
                report_date: issue ? issue.reported_date : "Unknown",
                project_due_date: project.project_due_date,
            };
        });
        const projectIds = allRows.map(row => row.id);

        const { data: existingPOs, error: poError } = await supabase
        .from("vb_purchase_orders")
        .select("project_id")
        .in("project_id", projectIds);

        if (poError) {
        console.error("Error fetching purchase orders:", poError);
        }

        const poProjectIds = new Set(existingPOs?.map(po => po.project_id));

        // Add purchase_order_exists flag
        allRows = allRows.map(row => ({
        ...row,
        purchase_order_exists: poProjectIds.has(row.id)
        }));
        if (searchTerm) {
            allRows = allRows.filter(row =>
                row.description_of_the_issue?.toLowerCase().includes(searchTerm) ||
                row.project_name?.toLowerCase().includes(searchTerm)
            );
        }

        if (issueError) {
            console.error("Error fetching available issues:", issueError);
            return;
        }
    }

    onMount(() => {
        fetchProjects();
        fetchPoItems();
        fetchActiveEmployees();
        fetchVillas();
    });

    $: currentPage = 1; // Reset to first page when allRows changes

    let showModal = false;
    let isEditing = false;
    let currentEditingId: string | null = null;
    let newProjects: Record<string, any> = {};
    let projectForUpdate: Record<string, any> | null = null;
    let dataIssueIds: Record<string, any>[] = [];
    const excludedKeys = [
        "id",
        "issue_id",
        "number_project",
        "input_by",
        "priority",
        "description_of_the_issue",
        "need_approval",
        "area_of_villa",
        "villa_name",
        "report_date",
        "actions",
        "project_name",
        "add_to_po",
        "issue_number",
        "updated_at",
        "updated_name",
        "input_name",
        "input_by",
    ];
    const formColumns = columns.filter(
        (col) => !excludedKeys.includes(col.key),
    );

    function openModal(project: Projects | null = null) {
        if (project) {
            isEditing = true;
            currentEditingId = project.id;
            newProjects = { ...project };
        } else {
            isEditing = false;
            currentEditingId = null;
            newProjects = {};
        }
        showModal = true;
        fetchIssueIds(); // Fetch issue IDs when opening the modal
    }

    //validation project make
    function validateProjectCheckBox(project: insertProject): boolean {
        if (!project.project_due_date) {
            console.error("Project due date is required");
            alert("Project due date is required");
            return false;
        }

        if (!project.picture_link) {
            console.error("Picture link is required");
            alert("Picture link is required");
            return false;
        }

        if (
            project.project_due_date &&
            isNaN(Date.parse(project.project_due_date))
        ) {
            console.error("Project due date must be a valid date");
            alert("Project due date must be a valid date");
            return false;
        }

        // if (
        //     project.picture_link &&
        //     !/^https?:\/\/.+\.(jpg|jpeg|png|gif)$/.test(project.picture_link)
        // ) {
        //     console.error("Picture link must be a valid image URL");
        //     alert("Picture link must be a valid image URL");
        //     return false;
        // }
        return true;
    }

    //get all id dan name from issues
    async function fetchIssueIds() {
        const { data, error } = await supabase
            .from("vb_issues")
            .select("id, description_of_the_issue")
            .order("id", { ascending: false });

        if (error) {
            console.error("Error fetching issues:", error);
            return;
        }

        dataIssueIds = data.map((issue) => ({
            id: issue.id,
            description_of_the_issue: issue.description_of_the_issue,
        }));
    }

    async function addToPo(project: Project) {
        // session user
        const session = await supabase.auth.getSession();
        const user = session?.data?.session?.user;
        if (!user) {
            console.error("User not authenticated");
            alert("User not authenticated");
            return;
        }

        const inputBy = user.id; // Use user id as input_by

        if (!project.add_to_po) {
            console.error("Project must be added to PO");
            alert("Project must be added to PO");
            return;
        }

        // Validate project before saving
        if (!validateProjectCheckBox(project)) {
            return;
        }
        projectForUpdate = {
            add_to_po: project?.add_to_po,
            input_by: project?.input_by,
            project_due_date: project?.project_due_date,
            picture_link: project?.picture_link,
            updated_at: new Date().toISOString(),
            updated_by: inputBy,
        };

        const { data, error } = await supabase
            .from("vb_projects")
            .update(projectForUpdate)
            .eq("id", currentEditingId);

        if (error) {
            console.error("Error updating project:", error);
            return;
        }

        alert("Add To PO Successfully");

        await fetchProjects();

        // tambah ke Purchase Order
        const { data: poData, error: poError } = await supabase
            .from("vb_purchase_orders")
            .insert({
                issue_id: project.issue_id,
                po_status: "REQUESTED",
            });
        if (poError) {
            console.error("Error adding to Purchase Order:", poError);
            return;
        }
    }

    // function get public URL for image supabase
    async function getPublicUrl(path: string): Promise<string> {
        const { data } = supabase.storage.from("villabugis").getPublicUrl(path);
        return data.publicUrl;
    }
    async function openPoModal(row) {
        const { data, error } = await supabase
            .from("vb_purchase_orders")
            .select("id")
            .eq("project_id", row.id)
            .maybeSingle();

        if (data) {
            alert("Purchase Order for this project already exists.");
            return;
        }
        newPurchaseOrder = {
            po_type: "project",
            po_status: "requested",
            project_id: row.id,
            issue_id: row.issue_id,
            villa_id: row.villa_id || "unknown",
            po_item: "",
            po_quantity: 1,
            requested_by: ""
        };

        if (!row.villa_id) {
            // Optional: fetch villa_id from vb_issues if missing
            const { data, error } = await supabase.from("vb_issues").select("villa_id").eq("id", row.issue_id).single();
            if (data) newPurchaseOrder.villa_id = data.villa_id;
        }

        showPoModal = true;
        addToPoInProgress.add(row.id);
    }
    async function saveProject(event: Event) {
        //get session user
        const session = await supabase.auth.getSession();
        const user = session?.data?.session?.user;
        if (!user) {
            console.error("User not authenticated");
            return;
        }

        const inputBy = user.id; // Use email or id as input_by

        const formData = new FormData(event.target as HTMLFormElement);

        // Upload image if selected
        if (selectedFile) {
            const oldFilePath = formData.get("picture_link") as string;
            if (oldFilePath) {
                // Delete old file if it exists
                const { error: deleteError } = await supabase.storage
                    .from("villabugis")
                    .remove([`project/${oldFilePath}`]);

                if (deleteError) {
                    console.error("Error deleting old image:", deleteError);
                    return;
                }
            }
            //randomize file name uuid
            const fileName = selectedFile.name;
            const fileExtension = fileName.split(".").pop();
            const randomFileName = `${crypto.randomUUID()}.${fileExtension}`;

            const { data, error } = await supabase.storage
                .from("villabugis")
                .upload(`project/${randomFileName}`, selectedFile);

            if (error) {
                console.error("Error uploading image:", error);
                return;
            }

            imagePreviewUrl = data?.path;
        }

        const projectUpdate: insertProject = {
            issue_id: formData.get("issue_id") as string,
            input_by: inputBy,
            project_due_date: formData.get("project_due_date") as string,
            picture_link:
                imagePreviewUrl || (formData.get("picture_link") as string),
            updated_at: new Date().toISOString(),
            updated_by: user.id,
        };

        // Validate project before saving
        if (!validateProjectCheckBox(projectUpdate)) {
            return;
        }

        console.log("current editing", currentEditingId);

        if (isEditing && currentEditingId) {
            const { data, error } = await supabase
                .from("vb_projects")
                .update(projectUpdate)
                .eq("id", currentEditingId);

            if (error) {
                console.error("Error updating project:", error);
                return;
            } else {
                alert("Project updated successfully");
            }
        } else {
            const { data, error } = await supabase
                .from("vb_projects")
                .insert(projectUpdate);

            if (error) {
                console.error("Error inserting project:", error);
                return;
            }
        }

        await fetchProjects();
        showModal = false;

        isEditing = false;
        currentEditingId = null;
        newProjects = {};
        imagePreviewUrl = null;
        selectedFile = null;
    }
    async function saveProjectEdit() {
        const session = await supabase.auth.getSession();
        const user = session?.data?.session?.user;

        if (!user) {
            console.error("User not authenticated");
            alert("You must be logged in to edit this project.");
            return;
        }

        // Format date
        const today = new Date();
        const formattedDate = `${today.getMonth() + 1}/${today.getDate()}/${today.getFullYear()}`;

        const { error } = await supabase
            .from("vb_projects")
            .update({
            project_name: projectEditForm.project_name,
            project_status: projectEditForm.project_status,
            project_comment: projectEditForm.project_comment,
            picture_link: projectEditForm.picture_link,
            assigned_to: projectEditForm.assigned_to,
            project_start_date: projectEditForm.project_start_date,
            project_due_date: projectEditForm.project_due_date,
            updated_at: formattedDate,
            updated_by: user.id  // ✅ real user info
            })
            .eq("project_number", projectEditForm.project_number);

        if (error) {
            console.error("Error saving project:", error);
            alert("Failed to save changes.");
            return;
        }

        showProjectEditModal = false;
        await fetchProjects();
    }




    async function deleteProject(id: string) {
        const confirmed = confirm("Are you sure you want to delete this project? This action cannot be undone.");
        if (!confirmed) {
            return;
        }

        const { error } = await supabase
            .from("vb_projects")
            .delete()
            .eq("id", id);

        if (error) {
            console.error("Error deleting project:", error);
            alert("Failed to delete project.");
            return;
        }

        alert("Project deleted successfully.");
        await fetchProjects();
    }
    async function savePurchaseOrder() {
        const { error } = await supabase.from("vb_purchase_orders").insert({
            po_type: newPurchaseOrder.po_type,
            po_status: newPurchaseOrder.po_status,
            project_id: newPurchaseOrder.project_id,
            issue_id: newPurchaseOrder.issue_id,
            villa_id: newPurchaseOrder.villa_id,
            po_item: newPurchaseOrder.po_item,
            po_quantity: newPurchaseOrder.po_quantity,
            requested_by: newPurchaseOrder.requested_by
        });

        if (error) {
            console.error("Error saving purchase order:", error);
            alert("Failed to save purchase order");
            return;
        }
        try {
            const webhookResponse = await fetch(
            "https://flow.catalis.app/webhook-test/vb_project_purchase",
            {
                method: "POST",
                headers: {
                "Content-Type": "application/json"
                },
                body: JSON.stringify({
                po_type: newPurchaseOrder.po_type,
                po_status: newPurchaseOrder.po_status,
                project_id: newPurchaseOrder.project_id,
                issue_id: newPurchaseOrder.issue_id,
                villa_id: newPurchaseOrder.villa_id,
                po_item: newPurchaseOrder.po_item,
                po_quantity: newPurchaseOrder.po_quantity,
                requested_by: newPurchaseOrder.requested_by
                })
            }
            );

            if (!webhookResponse.ok) {
            console.error("Webhook failed:", webhookResponse.statusText);
            }
        } catch (webhookError) {
            console.error("Webhook error:", webhookError);
        }

        alert("Purchase order added");
        showPoModal = false;
        addToPoInProgress.delete(newPurchaseOrder.project_id); // clear state
        await fetchProjects();
    }
</script>

<div>
    <div
        class="p-6 bg-white shadow-md rounded-2xl mb-4 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4"
    >
        <div>
            <h2 class="text-lg font-semibold text-gray-800">📋 Project List</h2>
            <p class="text-sm text-gray-600">
                Manage your projects and tasks efficiently.
            </p>
        </div>
        <div class="flex flex-col sm:flex-row sm:items-center gap-2">
            <input
                type="text"
                placeholder="🔍 Search by Issue..."
                class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-4 py-2 rounded-xl text-sm w-64 transition"
                on:input={(e) => {
                    const searchTerm = (
                        e.target as HTMLInputElement
                    ).value.toLowerCase();
                    fetchProjects(null, searchTerm, "created_at", "desc");
                }}
            />
            <select
                class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-4 py-2 rounded-xl text-sm w-48 transition"
                on:change={(e) => {
                    const filter = (e.target as HTMLSelectElement).value;
                    fetchProjects(filter, null, null, "desc");
                }}
            >
                <option value="">All Villas</option>
                {#each villas as villa}
                <option value={villa.villa_name}>{villa.villa_name}</option>
                {/each}
            </select>
            <button
                class="bg-gray-200 text-gray-700 px-4 py-2 rounded-xl hover:bg-gray-300 text-sm transition"
                on:click={() =>
                    fetchProjects(null, null, "created_at", "desc", 0, 10)}
            >
                🔄 Reset
            </button>
        </div>
    </div>
    <div class="overflow-x-auto rounded-lg shadow mb-4">
        <table class="min-w-[1000px] divide-y divide-gray-200 text-sm w-max">
            <thead class="bg-gray-100">
                <tr>
                    {#each columns as col}
                        {#if col.key === "description_of_the_issue"}
                            <th
                                class="sticky left-0 px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
                                style="background-color: #f0f8ff; z-index: 10;"
                            >
                                {col.title}
                            </th>
                        {:else}
                            <th
                                class="px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
                            >
                                {col.title}
                            </th>
                        {/if}
                    {/each}
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 bg-white">
                {#each paginatedRows as row}
                    <tr class="hover:bg-gray-50 transition">
                        {#each columns as col}
                            {#if col.key === "description_of_the_issue"}
                                <td
                                    class="sticky left-0 px-4 py-2 font-medium text-blue-600 max-w-xs whitespace-normal align-top break-words"
                                    style="background-color: #f0f8ff; cursor: pointer;"
                                >
                                    {row[col.key]}
                                </td>
                            {:else if col.key === "actions"}
                                <td class="px-4 py-2">
                                    <button
                                    class="inline-flex items-center gap-1 rounded px-3 py-1.5 text-xs font-medium 
                                        {row.purchase_order_exists ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-blue-600 text-white hover:bg-blue-700'}"
                                    on:click={() => openProjectEditModal(row)}
                                    disabled={row.purchase_order_exists}
                                    >
                                    ✏️ Edit
                                    </button>
                                    <button
                                    class="inline-flex items-center gap-1 rounded px-3 py-1.5 text-xs font-medium 
                                        {row.purchase_order_exists ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-red-600 text-white hover:bg-red-700'}"
                                    on:click={() => deleteProject(row.id)}
                                    disabled={row.purchase_order_exists}
                                    >
                                    🗑️ Delete
                                    </button>
                                </td>
                            {:else if col.key === "add_to_po"}
                            <td class="px-4 py-2 text-center">
                                {#if row.purchase_order_exists}
                                  <button class="bg-gray-300 text-gray-500 px-3 py-1.5 rounded cursor-not-allowed" disabled>
                                    PO Created
                                  </button>
                                {:else}
                                  <button
                                    class="inline-flex items-center gap-1 rounded bg-green-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-green-700 disabled:bg-gray-300"
                                    on:click={() => openPoModal(row)}
                                    disabled={addToPoInProgress.has(row.id)}
                                  >
                                    ➕ Add to PO
                                  </button>
                                {/if}
                              </td>
                            {:else if col.key === "need_approval"}
                                <td class="px-4 py-2">
                                    {#if row[col.key as keyof Projects]}
                                        ✅
                                    {:else}
                                        ❌
                                    {/if}
                                </td>
                            {:else if col.key === "picture_link"}
                                <td class="px-4 py-2">
                                    {#if row.picture_link}
                                        {#await getPublicUrl(row.picture_link) then publicUrl}
                                            <a
                                                href={publicUrl}
                                                target="_blank"
                                                class="text-blue-600 hover:underline"
                                                >View Picture</a
                                            >
                                        {:catch}
                                            <span class="text-red-500"
                                                >Error loading image</span
                                            >
                                        {/await}
                                    {:else}
                                        No Picture
                                    {/if}
                                </td>
                            {:else if col.key === "project_due_date"}
                                <td class="px-4 py-2">
                                    {#if row.project_due_date}
                                        {new Date(
                                            row.project_due_date,
                                        ).toLocaleString("en-US")}
                                    {:else}
                                        No Due Date
                                    {/if}
                                </td>
                            {:else if col.key === "updated_at"}
                                <td class="px-4 py-2">
                                    {#if row.updated_at}
                                        {new Date(
                                            row.updated_at,
                                        ).toLocaleString("en-US")}
                                    {:else}
                                        No Update
                                    {/if}
                                </td>
                            {:else if col.key === "input_by"}
                                <td class="px-4 py-2">
                                    {#if row.input_by}
                                        {row.input_by}
                                    {:else}
                                        Not Yet Input
                                    {/if}
                                </td>
                            {:else if col.key === "updated_name"}
                                <td class="px-4 py-2">
                                    {#if row.updated_name}
                                        {row.updated_name}
                                    {:else}
                                        No Updater
                                    {/if}
                                </td>
                            {:else}
                                <td class="px-4 py-2 text-gray-700  max-w-xs whitespace-normal align-top break-words left-0 "
                                    >{row[col.key as keyof Projects]}</td
                                >
                            {/if}
                        {/each}
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>

    <!-- Pagination controls -->
    <div class="flex justify-between items-center text-sm">
        <div>
            Showing {(currentPage - 1) * rowsPerPage + 1}–{Math.min(currentPage * rowsPerPage, allRows.length)}
            of {allRows.length}
          </div>
          <Pagination {totalPages} {currentPage} {goToPage} />
    </div>
</div>

{#if showModal}
    <div
        class="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 z-50"
    >
        <div
            class="bg-white p-6 rounded shadow-lg w-[600px] max-h-[90vh] overflow-y-auto space-y-4"
        >
            <h3 class="text-lg font-semibold mb-4">
                {isEditing ? "Edit Project" : "Add Project"}
            </h3>
            <form on:submit|preventDefault={saveProject}>
                {#each formColumns as col}
                    {#if col.key === "project_due_date"}
                        <div class="mb-4">
                            <label
                                for={col.key}
                                class="block text-sm font-medium text-gray-700 mb-1"
                            >
                                {col.title}
                            </label>
                            <input
                                name={col.key}
                                type="date"
                                id={col.key}
                                bind:value={newProjects[col.key]}
                                class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring focus:ring-blue-500"
                            />
                        </div>
                    {:else if col.key === "picture_link"}
                        <!-- image upload -->
                        <div class="mb-4">
                            <label
                                for={col.key}
                                class="block text-sm font-medium text-gray-700 mb-1"
                            >
                                {col.title}
                            </label>
                            <input
                                name="picture_link"
                                class="w-full border px-3 py-2 rounded"
                                type="file"
                                accept="image/*"
                                on:change={handleFileChange}
                            />
                            <p class="text-xs text-gray-500">
                                Upload an image related to the issue.
                            </p>

                            {#if imagePreviewUrl}
                                <img
                                    src={imagePreviewUrl}
                                    alt="Preview"
                                    class="mt-2 max-h-48 rounded border"
                                />
                            {:else if newProjects.picture_link}
                                {#await getPublicUrl(newProjects.picture_link) then url}
                                    <img
                                        src={url}
                                        alt="Preview"
                                        class="mt-2 max-h-48 rounded border"
                                    />
                                {/await}
                            {:else}
                                <p class="text-red-500 mt-2">
                                    No image selected or uploaded.
                                </p>
                            {/if}
                        </div>
                    {:else}
                        <div class="mb-4">
                            <label
                                for={col.key}
                                class="block text-sm font-medium text-gray-700 mb-1"
                            >
                                {col.title}
                            </label>
                            <input
                                name={col.key}
                                type="text"
                                id={col.key}
                                bind:value={newProjects[col.key]}
                                class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring focus:ring-blue-500"
                            />
                        </div>
                    {/if}
                {/each}
                <!-- list issue dan bisa mencari -->
                <div class="mb-4">
                    <label
                        for="issue_id"
                        class="block text-sm font-medium text-gray-700 mb-1"
                    >
                        Issue ID
                    </label>
                    <select
                        id="issue_id"
                        name="issue_id"
                        required
                        bind:value={newProjects.issue_id}
                        class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring focus:ring-blue-500"
                    >
                        <option value="" disabled selected>Select Issue</option>
                        {#each dataIssueIds as issueId}
                            <option value={issueId.id}>{issueId.description_of_the_issue}</option>
                        {/each}
                    </select>
                </div>
                <div class="flex justify-end space-x-2">
                    <button
                        type="button"
                        class="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
                        on:click={() => (showModal = false)}
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                    >
                        Save
                    </button>
                </div>
            </form>
        </div>
    </div>
{/if}
{#if showPoModal}
  <div class="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 z-50">
    <div class="bg-white p-6 rounded shadow-lg w-[400px]">
      <h3 class="text-lg font-semibold mb-4">Add to Purchase Order</h3>
      <form on:submit|preventDefault={savePurchaseOrder}>
        <!-- Hidden fields -->
        <input type="hidden" name="po_type" value={newPurchaseOrder.po_type} />
        <input type="hidden" name="po_status" value={newPurchaseOrder.po_status} />
        <input type="hidden" name="issue_id" value={newPurchaseOrder.issue_id} />
        <input type="hidden" name="villa_id" value={newPurchaseOrder.villa_id} />

        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1">Item</label>
          <select bind:value={newPurchaseOrder.po_item} required class="w-full border px-2 py-2 rounded">
            <option value="">Select Item</option>
            {#each poItems as item}
              <option value={item.item_name}>{item.item_name}</option>
            {/each}
          </select>
        </div>

        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-1">Quantity</label>
          <input type="number" bind:value={newPurchaseOrder.po_quantity} min="1" class="w-full border px-2 py-2 rounded" required/>
        </div>
        <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">Requested By</label>
            <select bind:value={newPurchaseOrder.requested_by} required class="w-full border px-2 py-2 rounded">
              <option value="">Select Employee</option>
              {#each employees as emp}
                <option value={emp.id}>{emp.employee_name}</option>
              {/each}
            </select>
        </div>
        <div class="flex justify-end space-x-2">
          <button type="button" on:click={() => showPoModal = false} class="px-4 py-2 bg-gray-200 rounded">Cancel</button>
          <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded">Submit</button>
        </div>
      </form>
    </div>
  </div>
{/if}

{#if showEditModal}
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto">
    <div class="min-h-screen flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6 space-y-4">
        <h2 class="text-xl font-bold">Edit Purchase Order</h2>

        <!-- PO Number -->
        <label>PO Number</label>
        <input type="text" value={editForm.po_number} disabled class="w-full border p-2 bg-gray-100"/>

        <!-- Issue Name -->
        <label>Issue Name</label>
        <input type="text" value={editForm.issue_name} disabled class="w-full border p-2 bg-gray-100"/>

        <!-- Villa ID -->
        <label>Villa ID</label>
        <input type="text" value={editForm.villa_id} disabled class="w-full border p-2 bg-gray-100"/>

        <!-- PO Status -->
        <label>PO Status</label>
        <input type="text" value={editForm.po_status} disabled class="w-full border p-2 bg-gray-100"/>

        <!-- Status Toggles -->
        <div class="space-y-2">
          {#each ['prepared','approved','acknowledged','completed','received'] as key}
            <div class="flex items-center gap-2">
              <label class="w-32 capitalize">{key}</label>
              <select bind:value={editForm[key]} class="w-40 border p-2">
                <option value={null}>Unset</option>
                <option value={true}>True</option>
                <option value={false}>False</option>
              </select>
              <button
                type="button"
                class="text-xs text-blue-600 underline"
                on:click={() => editForm[key] = null}
              >Reset</button>
            </div>
          {/each}
        </div>

        <!-- PO Remark -->
        <label>PO Remark</label>
        <textarea
          bind:value={editForm.po_remark}
          class="w-full border p-2"
          rows="3"
        ></textarea>

        <!-- Actions -->
        <div class="flex justify-end space-x-2 pt-4">
          <button on:click={saveEdit} class="bg-blue-600 text-white px-4 py-2 rounded">Save</button>
          <button on:click={() => showEditModal = false} class="px-4 py-2 rounded border">Cancel</button>
        </div>
      </div>
    </div>
  </div>
{/if}
{#if showProjectEditModal}
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto">
    <div class="min-h-screen flex items-center justify-center p-4">
      <div class="bg-white rounded-2xl shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto p-8 space-y-6">
        
        <h2 class="text-2xl font-semibold text-gray-800">🛠️ Edit Project</h2>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- Left Column -->
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Project Number</label>
              <input type="text" value={projectEditForm.project_number} disabled class="w-full border p-2 bg-gray-100 rounded" />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Issue Description</label>
              <textarea value={projectEditForm.issue_desc} disabled class="w-full border p-2 bg-gray-100 rounded resize-none" rows="3" />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Project Name</label>
              <input type="text" bind:value={projectEditForm.project_name} class="w-full border p-2 rounded" />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Project Status</label>
              <select bind:value={projectEditForm.project_status} class="w-full border p-2 rounded">
                <option value="On Progress">On Progress</option>
                <option value="Done">Done</option>
              </select>
            </div>

            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Picture Link</label>
                <input type="text" bind:value={projectEditForm.picture_link} class="w-full border p-2 rounded" />
            </div>
          </div>

          <!-- Right Column -->
          <div class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                <input type="date" bind:value={projectEditForm.project_start_date} class="w-full border p-2 rounded" />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Due Date</label>
              <input type="date" bind:value={projectEditForm.project_due_date} class="w-full border p-2 rounded" />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Assigned To</label>
              <select bind:value={projectEditForm.assigned_to} class="w-full border p-2 rounded">
                <option value="">Select Employee</option>
                {#each employees as emp}
                  <option value={emp.id}>{emp.employee_name}</option>
                {/each}
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Project Comment</label>
              <textarea bind:value={projectEditForm.project_comment} rows="4" class="w-full border p-2 rounded"></textarea>
            </div>
          </div>
        </div>

        <div class="flex justify-end gap-3 pt-4">
          <button on:click={() => showProjectEditModal = false} class="px-4 py-2 rounded border text-gray-700 hover:bg-gray-100">Cancel</button>
          <button on:click={saveProjectEdit} class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Save</button>
        </div>

      </div>
    </div>
  </div>
{/if}


