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

    const priority = [
        { label: "Low", value: "Low" },
        { label: "Medium", value: "Medium" },
        { label: "High", value: "High" },
        { label: "Critical", value: "Critical" },
    ];
    const issueSource = [
        { label: "Guest Assistant", value: "Guest Assistant" },
        { label: "Villa Attendant", value: "Villa Attendant" },
        { label: "Villa Supervisor", value: "Villa Supervisor" },
        { label: "Villa Manager", value: "Villa Manager" },
        { label: "Operation Manager", value: "Operation Manager" },
        { label: "Quality Control Manager", value: "Quality Control Manager" },
        { label: "Owner", value: "Owner" },
        { label: "Sales/Reservations", value: "Sales/Reservations" },
        { label: "Guest", value: "Guest" },
        { label: "Agent", value: "Agent" },
    ];
    const issueTypes = [
        { label: "Facilities - Air Conditioner", value: "Facilities - Air Conditioner" },
        { label: "Facilities - Appliances", value: "Facilities - Appliances" },
        { label: "Facilities - Baby Cot", value: "Facilities - Baby Cot" },
        { label: "Facilities - Bath", value: "Facilities - Bath" },
        { label: "Facilities - Bed", value: "Facilities - Bed" },
        { label: "Facilities - Blender", value: "Facilities - Blender" },
        { label: "Facilities - Cabinet", value: "Facilities - Cabinet" },
        { label: "Facilities - Cable TV", value: "Facilities - Cable TV" },
        { label: "Facilities - CCTV", value: "Facilities - CCTV" },
        { label: "Facilities - Ceiling Fans", value: "Facilities - Ceiling Fans" },
        { label: "Facilities - Coffee Maker", value: "Facilities - Coffee Maker" },
        { label: "Facilities - DVD", value: "Facilities - DVD" },
        { label: "Facilities - Generator", value: "Facilities - Generator" },
        { label: "Facilities - Hairdryer", value: "Facilities - Hairdryer" },
        { label: "Facilities - Home Theatre", value: "Facilities - Home Theatre" },
        { label: "Facilities - Hot Water", value: "Facilities - Hot Water" },
        { label: "Facilities - Internet Connection", value: "Facilities - Internet Connection" },
        { label: "Facilities - Iron/Ironing Board", value: "Facilities - Iron/Ironing Board" },
        { label: "Facilities - Kitchen Equipment", value: "Facilities - Kitchen Equipment" },
        { label: "Facilities - Lights", value: "Facilities - Lights" },
        { label: "Facilities - Linen", value: "Facilities - Linen" },
        { label: "Facilities - Mattress", value: "Facilities - Mattress" },
        { label: "Facilities - Mirror", value: "Facilities - Mirror" },
        { label: "Facilities - Mosquito Net", value: "Facilities - Mosquito Net" },
        { label: "Facilities - Other", value: "Facilities - Other" },
        { label: "Facilities - Parking", value: "Facilities - Parking" },
        { label: "Facilities - Pool Umbrella", value: "Facilities - Pool Umbrella" },
        { label: "Facilities - Safe Deposit Box", value: "Facilities - Safe Deposit Box" },
        { label: "Facilities - Security", value: "Facilities - Security" },
        { label: "Facilities - Shower", value: "Facilities - Shower" },
        { label: "Facilities - Sink", value: "Facilities - Sink" },
        { label: "Facilities - Sunbed and Mattress", value: "Facilities - Sunbed and Mattress" },
        { label: "Facilities - Swimming Pool", value: "Facilities - Swimming Pool" },
        { label: "Facilities - Telephone", value: "Facilities - Telephone" },
        { label: "Facilities - Toaster", value: "Facilities - Toaster" },
        { label: "Facilities - Toilet Bowl", value: "Facilities - Toilet Bowl" },
        { label: "Facilities - Toiletries", value: "Facilities - Toiletries" },
        { label: "Facilities - Towels", value: "Facilities - Towels" },
        { label: "Facilities - TV Unit", value: "Facilities - TV Unit" },
        { label: "Facilities - Wardrobe", value: "Facilities - Wardrobe" },
        { label: "Facilities - Wash Basin", value: "Facilities - Wash Basin" },
        { label: "Facilities - Water Dispenser", value: "Facilities - Water Dispenser" },
        { label: "Maintenance - Civil", value: "Maintenance - Civil" },
        { label: "Maintenance - Electrical", value: "Maintenance - Electrical" },
        { label: "Maintenance - Mechanical", value: "Maintenance - Mechanical" },
        { label: "Maintenance - Painting", value: "Maintenance - Painting" },
        { label: "Maintenance - Plumbing", value: "Maintenance - Plumbing" },
        { label: "Maintenance - Roof", value: "Maintenance - Roof" },
        { label: "Other - Accident", value: "Other - Accident" },
        { label: "Other - Animals", value: "Other - Animals" },
        { label: "Other - Booking", value: "Other - Booking" },
        { label: "Other - Cleanliness", value: "Other - Cleanliness" },
        { label: "Other - Crime", value: "Other - Crime" },
        { label: "Other - Food and Beverage", value: "Other - Food and Beverage" },
        { label: "Other - Garden", value: "Other - Garden" },
        { label: "Other - Inventory", value: "Other - Inventory" },
        { label: "Other - Noise", value: "Other - Noise" },
        { label: "Other - Payment", value: "Other - Payment" },
        { label: "Other - Transport", value: "Other - Transport" },
    ];
    const areaOfVilla = [
        { label: "All Bathrooms", value: "All Bathrooms" },
        { label: "All Guest Houses", value: "All Guest Houses" },
        { label: "All Rooms", value: "All Rooms" },
        { label: "All Villa Areas", value: "All Villa Areas" },
        { label: "Balcony", value: "Balcony" },
        { label: "Bathroom (Guest)", value: "Bathroom (Guest)" },
        { label: "Bathroom Guest House 1", value: "Bathroom Guest House 1" },
        { label: "Bathroom Guest House 2", value: "Bathroom Guest House 2" },
        { label: "Bathroom Guest House 3", value: "Bathroom Guest House 3" },
        { label: "Bathroom (Master)", value: "Bathroom (Master)" },
        { label: "Bathroom 1", value: "Bathroom 1" },
        { label: "Bathroom 2", value: "Bathroom 2" },
        { label: "Bathroom 3", value: "Bathroom 3" },
        { label: "Bathroom 4", value: "Bathroom 4" },
        { label: "Bathroom 5", value: "Bathroom 5" },
        { label: "BBQ Area", value: "BBQ Area" },
        { label: "Bedroom (Master)", value: "Bedroom (Master)" },
        { label: "Bedroom 1", value: "Bedroom 1" },
        { label: "Bedroom 2", value: "Bedroom 2" },
        { label: "Bedroom 3", value: "Bedroom 3" },
        { label: "Bedroom 4", value: "Bedroom 4" },
        { label: "Bedroom 5", value: "Bedroom 5" },
        { label: "Boundary Wall", value: "Boundary Wall" },
        { label: "Carport", value: "Carport" },
        { label: "Dining Room", value: "Dining Room" },
        { label: "Flat Roof", value: "Flat Roof" },
        { label: "Garden", value: "Garden" },
        { label: "Gate", value: "Gate" },
        { label: "Gazebo", value: "Gazebo" },
        { label: "Generator Room", value: "Generator Room" },
        { label: "Guest House 1", value: "Guest House 1" },
        { label: "Guest House 2", value: "Guest House 2" },
        { label: "Guest House 3", value: "Guest House 3" },
        { label: "Guest House 4", value: "Guest House 4" },
        { label: "Kids Room", value: "Kids Room" },
        { label: "Kitchen", value: "Kitchen" },
        { label: "Landscape", value: "Landscape" },
        { label: "Living Room", value: "Living Room" },
        { label: "Other", value: "Other" },
        { label: "Outdoor Bar", value: "Outdoor Bar" },
        { label: "Outdoor Kitchen", value: "Outdoor Kitchen" },
        { label: "Outdoor Shower", value: "Outdoor Shower" },
        { label: "Outside The Villa", value: "Outside The Villa" },
        { label: "Pool", value: "Pool" },
        { label: "Pump Room", value: "Pump Room" },
        { label: "Staff Room", value: "Staff Room" },
        { label: "Stairs (other)", value: "Stairs (other)" },
        { label: "Stairs (living room)", value: "Stairs (living room)" },
        { label: "Storage", value: "Storage" },
        { label: "Transport", value: "Transport" },
        { label: "TV Room", value: "TV Room" },
        { label: "Water Feature", value: "Water Feature" }
    ];
    const columns: columns[] = [
        
        { key: "issue_number", title: "Issue Number" },
        { key: "description_of_the_issue", title: "Description of The Issue" },
        { key: "villa_name", title: "Villa Name" },
        { key: "villa_id", title: "Villa ID" },
        { key: "input_by", title: "Input By" },
        { key: "reported_by", title: "Reported By" },
        { key: "reported_date", title: "Reported Date" },
        { key: "area_of_villa", title: "Area Of Villa" },
        { key: "priority", title: "Priority" },
        { key: "issue_type", title: "Issue Type" },
        { key: "move_issue", title: "Move Issue" },
        { key: "issue_related_image", title: "Issue Related Image" },
        { key: "url_drive", title: "URL Drive" },
        { key: "issue_source", title: "Issue Source" },
        { key: "reported_name", title: "Reported By" },
        { key: "inputed_name", title: "Input By" },
        { key: "guest_communication", title: "Guest Communication" },
        { key: "resolution", title: "Resolved How?" },
        { key: "need_approval", title: "Need Approval" },
        { key: "status", title: "Status" },
        { key: "created_at", title: "Created At" },
        { key: "updated_name", title: "Updated By" },
        { key: "updated_at", title: "Updated At" },
        { key: "actions", title: "Actions" },
    ];
    const excludedKeys = [
        "id",
        "created_at",
        "move_issue",
        "issue_number",
        "actions",
        "villa_name",
        "reported_name",
        "inputed_name",
        "updated_name",
        "updated_at",
        "updated_by",
    ];
    const excludedKeysDisplay = [
        "villa_id",
        "reported_by",
        "input_by",
        "updated_by",
    ];
    const formColumns = columns.filter(
        (col) => !excludedKeys.includes(col.key),
    );

    const formColumnsDisplay = columns.filter(
        (col) => !excludedKeysDisplay.includes(col.key),
    );

    // Define types for the data structures
    type PurchaseOrder = {
        villa_id: string;
        issue_id: string;
        po_status: string;
        requested_by: string;
        requested_date: string;
        po_due: string;
        po_item: string;
        po_quantity: string;
        po_type: string;
    };
    type Villa = {
        id: string;
        villa_name: string;
    };
    type User = {
        id: string;
        employee_name: string;
    };
    type Issue = {
        id: string;
        villa_id: string;
        villa_name: string;
        area_of_villa: string;
        priority: string;
        issue_type: string;
        issue_number: string;
        move_issue: string;
        description_of_the_issue: string;
        reported_date: string;
        issue_related_image: string;
        url_drive: string;
        issue_source: string;
        reported_by: string;
        input_by: string;
        guest_communication: string;
        resolution: string;
        need_approval: boolean;
        status: boolean;
        created_at: string;
        updated_by?: string;
        updated_at?: string;
    };
    type issueInsert = {
        villa_id: string;
        area_of_villa: string;
        priority: string;
        issue_type: string;
        description_of_the_issue: string;
        reported_date: string;
        issue_related_image: string;
        url_drive?: string; // Optional, if not always present
        issue_source: string;
        reported_by: string;
        input_by: string;
        guest_communication: string;
        resolution: string;
        need_approval: boolean;
        status?: boolean; // default to false if not set
    };
    type POItem = {
        item_name: string;
    };
    type columns = {
        key: string;
        title: string;
    };

    // Reactive variables
    let currentVillaFilter: string | null = "";
    let currentSearchTerm: string | null = null;
    let showProjectModal = false;
    let selectedIssueId: string | null = null;
    let showPurchaseOrderModal = false;
    let dataVilla: Villa[] = [];
    let dataUser: User[] = [];
    let projectIssueMap: Set<string> = new Set();
    let purchaseOrderMap: Set<string> = new Set();
    let sortColumn: string | null = "created_at"; // or any default column
    let sortOrder: "asc" | "desc" = "desc";
    let poItems: POItem[] = [];
    let newPO: PurchaseOrder = {
        villa_id: "",
        issue_id: "",
        po_status: "requested",
        requested_by: "",
        requested_date: "",
        po_due: "",
        po_item: "",
        po_quantity: "",
        po_type: ""
    };
    let newProject = {
        project_name: "",
        issue_id: "",
        input_by: "",
        project_due_date: "",
        assigned_to: "",
        project_comment: ""
    };
    let allRows: Issue[] = [];
    let showModal = false;
    let isEditing = false;
    let selectedFile: File | null = null;
    let imagePreviewUrl: string | null = null;
    let currentEditingId: string | null = null;
    let newIssue: Record<string, any> = {};
    let selectedIssueSummary = "";
    let offset = 0;
    let limit = 10;
    let totalItems = 0;
    let currentPage = offset + 1;
    let rowsPerPage = limit;
    let filteredRows: Issue[] = [];
    $: paginatedRows = filteredRows.slice(
        (currentPage - 1) * rowsPerPage,
        currentPage * rowsPerPage
        );

    $: totalItems = filteredRows.length;
    $: totalPages = Math.ceil(totalItems / rowsPerPage);
    $: {
        let rows = allRows;

        if (currentVillaFilter) {
            rows = rows.filter(r => r.villa_id === currentVillaFilter);
        }

        if (currentSearchTerm && currentSearchTerm.trim() !== "") {
            const term = currentSearchTerm.toLowerCase();
            rows = rows.filter(r =>
            (r.description_of_the_issue || "").toLowerCase().includes(term)
            );
        }

        filteredRows = rows;
        currentPage = 1; // Optional: reset page when filter/search changes
    }
    // Fetch existing project links and purchase orders
    async function fetchExistingProjectLinks() {
        const { data, error } = await supabase
            .from("vb_projects")
            .select("issue_id");
        if (!error && data) {
            projectIssueMap = new Set(data.map((p) => p.issue_id));
        } else {
            console.error("Error loading existing projects:", error);
        }
    }
    // Fetch existing purchase orders
    async function fetchExistingPurchaseOrders() {
        const { data } = await supabase.from("vb_purchase_orders").select("issue_id");
        if (data) purchaseOrderMap = new Set(data.map(p => p.issue_id));
    }
    // Fetch PO items
    async function fetchPoItems() {
        const { data } = await supabase.from("vb_po_item").select("item_name");
        if (data) poItems = data;
    }
    function getDBColumn(key: string) {
        switch (key) {
            case "villa_name": return "villa_name";
            case "reported_by": return "reported_by";
            // add mappings if needed
            default: return key;
        }
    }
    // Fetch issues with optional filters
    async function fetchIssues() {
        let query = supabase
            .from("vb_issues_data")
            .select("*")
            .order(sortColumn || "created_at", { ascending: sortOrder === "asc" });

        const { data: issues, error } = await query;

        if (error) {
            console.error(error);
            return;
        }

        allRows = issues || [];
    }

    // Function to handle form submission and save issue
    async function saveIssue(event: Event) {
        const session = await supabase.auth.getSession();
        const userId = session.data.session?.user.id;

        newIssue.updated_by = userId;
        newIssue.updated_at = new Date().toISOString();
        event.preventDefault();

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

        // Validate form data
        if (!validateForm(formData)) {
            console.error("Form validation failed");
            return;
        }

        //upload image if selected
        if (selectedFile) {
            //delete previous image
            const oldFilePath = newIssue.issue_related_image
                ? newIssue.issue_related_image.split("/").pop()
                : null;
            if (oldFilePath) {
                const { error: deleteError } = await supabase.storage
                    .from("villabugis")
                    .remove([`issues/${oldFilePath}`]);
                if (deleteError) {
                    console.error("Error deleting old image:", deleteError);
                }
            }

            const fileName = selectedFile.name;
            const fileExtension = fileName.split(".").pop();
            const randomFileName = `${crypto.randomUUID()}.${fileExtension}`;

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

            console.log("Image upload data:", data);

            if (error) {
                alert("Error uploading image: " + error.message);
                console.error("Error uploading image:", error);
                return;
            }
            newIssue.issue_related_image = data.path;
        }

        if (isEditing && currentEditingId) {
            const session = await supabase.auth.getSession();
            const userId = session.data.session?.user.id;
            const reducedIssue = formColumns.reduce(
                (acc, col) => {
                    if (col.key in newIssue) {
                        acc[col.key] = newIssue[col.key];
                    }
                    return acc;
                },
                {} as Record<string, any>,
            );

            // Add system fields
            reducedIssue.updated_by = userId;
            reducedIssue.updated_at = new Date().toISOString();

            const { error } = await supabase
                .from("vb_issues")
                .update(reducedIssue)
                .eq("id", currentEditingId);

            if (error) {
                alert("Error updating issue: " + error.message);
                console.error("Error updating issue:", error);
                return;
            } else {
                alert("Issue updated successfully.");
            }
        } else {
            const issueInsert: issueInsert = {
                villa_id: formData.get("villa_id") as string,
                area_of_villa: formData.get("area_of_villa") as string,
                priority: formData.get("priority") as string,
                issue_type: formData.get("issue_type") as string,
                description_of_the_issue: formData.get(
                    "description_of_the_issue",
                ) as string,
                reported_date: formData.get("reported_date") as string,
                issue_related_image: newIssue.issue_related_image
                    ? newIssue.issue_related_image
                    : (formData.get("issue_related_image") as string),
                url_drive: formData.get("url_drive") as string,
                issue_source: formData.get("issue_source") as string,
                reported_by: formData.get("reported_by") as string,
                input_by: formData.get("input_by") as string,
                guest_communication: formData.get(
                    "guest_communication",
                ) as string,
                resolution: formData.get("resolution") as string,
                need_approval: newIssue.need_approval,
                status: newIssue.status ?? false, // default to false if not set
            };

            const { error } = await supabase
                .from("vb_issues")
                .insert([issueInsert]);
            if (error) {
                console.error("Error adding issue:", error);
                return;
            } else {
                alert("Issue added successfully.");
            }
        }

        await fetchIssues();
        showModal = false;

        //clear form data
        newIssue = {};

        selectedFile = null;
        imagePreviewUrl = null;
    }
    // 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;
    }
    // Function to handle issue deletion
    async function deleteIssue(id: string) {
        if (projectIssueMap.has(id)) {
            alert("This issue is linked to a project and cannot be deleted.");
            return;
        }

        const confirmDelete = confirm("Are you sure you want to delete this issue?");
        if (!confirmDelete) return;

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

        if (error) {
            console.error("Delete failed:", error);
            alert("Failed to delete issue.");
        } else {
            await fetchIssues();
            alert("Issue deleted.");
        }
    }
    // Function to submit project
    async function submitProject() {
        if (!newProject.project_name || !newProject.input_by || !newProject.assigned_to) {
            alert("Please fill all required fields");
            return;
        }

        // Prevent duplicate
        const { data: existing, error: checkError } = await supabase
            .from("vb_projects")
            .select("id")
            .eq("issue_id", newProject.issue_id)
            .maybeSingle();

        if (existing) {
            alert("This issue already has a project assigned.");
            return;
        }

        // Insert into Supabase
        const { data, error } = await supabase.from("vb_projects").insert({
            project_name: newProject.project_name,
            issue_id: newProject.issue_id,
            input_by: newProject.input_by,
            project_due_date: new Date(newProject.project_due_date).toISOString(),
            assigned_to: newProject.assigned_to,
            project_comment: newProject.project_comment
        }).select().single(); // grab inserted data

        if (error) {
            console.error("Insert error:", error);
            alert("Failed to create project.");
            return;
        }

        // 🔥 Fire webhook
        try {
            await fetch("https://flow.catalis.app/webhook-test/vb-project-new", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(data) // or customize the payload as needed
            });
        } catch (webhookError) {
            console.error("Webhook error:", webhookError);
            alert("Project saved, but failed to notify webhook.");
        }
        
        projectIssueMap = new Set([...projectIssueMap, newProject.issue_id]);
        alert("Project created successfully.");
        showProjectModal = false;
    }
    // Function to submit purchase order
    async function submitPurchaseOrder() {
        if (!newPO.requested_by || !newPO.po_type) {
            alert("Please complete all required fields.");
            return;
        }

        const { data: existing } = await supabase
            .from("vb_purchase_orders")
            .select("id")
            .eq("issue_id", newPO.issue_id)
            .maybeSingle();

        if (existing) {
            alert("Purchase order already exists for this issue.");
            return;
        }

        const { error } = await supabase.from("vb_purchase_orders").insert(newPO);

        if (error) {
            console.error(error);
            alert("Failed to create PO.");
            return;
        }

        // reactively update map
        purchaseOrderMap = new Set([...purchaseOrderMap, newPO.issue_id]);

        alert("Purchase Order submitted!");
        showPurchaseOrderModal = false;
    }
    function toggleSort(column: string) {
        if (sortColumn === column) {
            sortOrder = sortOrder === "asc" ? "desc" : "asc";
        } else {
            sortColumn = column;
            sortOrder = "asc";
        }
        fetchIssues(); // re-fetch or re-sort your rows
    }
    // Function to open purchase order modal
    function openPurchaseOrderModal(issue) {
        if (purchaseOrderMap.has(issue.id)) {
            alert("This issue already has a purchase order.");
            return;
        }

        const today = new Date();
        const dueDate = new Date(today);
        dueDate.setDate(dueDate.getDate() + 2);

        const formatDate = (d) => d.toISOString().split("T")[0];

        newPO = {
            issue_id: issue.id,
            villa_id: issue.villa_id,
            po_status: "requested",
            requested_by: "",
            requested_date: formatDate(today),
            po_due: formatDate(dueDate),
            po_type: ""
        };

        selectedIssueSummary = issue.description_of_the_issue ?? "";
        showPurchaseOrderModal = true;
    }
    // Function to open project modal
    function openProjectModal(issue: Issue) {
        const dueDate = new Date(issue.created_at);
        dueDate.setDate(dueDate.getDate() + 2);

        selectedIssueSummary = issue.description_of_the_issue ?? "";

        newProject = {
            project_name: "",
            issue_id: issue.id,
            input_by: "", // can be prefilled if desired
            project_due_date: dueDate.toISOString().split("T")[0], // mm/dd/yyyy
            assigned_to: "",
            project_comment: ""
        };

        showProjectModal = true;
    }
    // Pagination functions
    function goToPage(page: number) {
        if (page >= 1 && page <= totalPages) currentPage = page;
    }
    // Function to handle page change
    function openModal(issue?: Record<string, any>) {
        if (issue) {
            if (projectIssueMap.has(issue.id)) {
                alert("This issue is linked to a project and cannot be edited.");
                return;
            }
            isEditing = true;
            currentEditingId = issue.id;
            newIssue = { ...issue };
        } else {
            isEditing = false;
            currentEditingId = null;
            newIssue = {};
        }
        showModal = true;
    }
    // Function to handle file input change
    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);
        }
    }
    // Function to validate form data
    function validateForm(formData: FormData): boolean {
        const errors: { [key: string]: string } = {};
        const requiredFields = [
            "description_of_the_issue",
            "issue_source",
            "villa_id",
            "reported_date",
            "reported_by",
            "priority",
            "issue_type",
            "input_by",
            "area_of_villa",
            "status",
        ];

        requiredFields.forEach((field) => {
            if (!formData.get(field) || formData.get(field) === "") {
                errors[field] = `${field.replace(/_/g, " ")} is required.`;
            }
        });

        formErrors.set(errors);
        return Object.keys(errors).length === 0;
    }
    // Function to get error class for form fields
    function errorClass(field: string): string {
        return $formErrors[field] ? "border-red-500" : "border";
    }


    // Fetch villas and users on mount
    onMount(async () => {
        await fetchExistingProjectLinks();
        const { data, error } = await supabase
            .from("vb_villas")
            .select("id, villa_name, villa_status")
            .eq("villa_status", "Active");

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

        const { data: userData, error: userError } = await supabase
            .from("vb_employee")
            .select("id, employee_name, employee_status")
            .eq("employee_status", "Active");
        if (userError) {
            console.error("Error fetching users:", userError);
        } else if (userData) {
            dataUser = userData;
        }
    });

    // Fetch issues, PO items, and existing purchase orders on mount
    onMount(() => {
        fetchIssues();    
        fetchPoItems();
        fetchExistingPurchaseOrders();
    });

    // Reactive store for form errors
    export let formErrors = writable<{ [key: string]: string }>({});
</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-xl font-semibold text-gray-800">📝 Issue List</h2>
            <p class="text-sm text-gray-500">
                Manage and view all issues reported in the system.
            </p>
        </div>

        <div class="flex flex-col sm:flex-row sm:items-center gap-2">
            <input
                type="text"
                id="issue-search"
                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"
                bind:value={currentSearchTerm}

            />
            <select
                id="villa-filter"
                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"
                bind:value={currentVillaFilter}
                >
                    <option value="">All Villas</option>
                    {#each dataVilla as villa}
                        <option value={villa.id}>{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={() =>{
                currentVillaFilter = "";
                currentSearchTerm = "";
                }}
            >
                🔄 Reset
            </button>
            <button
                class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 text-sm"
                on:click={() => openModal()}
            >
                ➕ Add Issue
            </button>
        </div>
    </div>
    <div class="overflow-x-auto rounded-lg shadow mb-4 max-h-[70vh]">
        <table class="min-w-[1000px] divide-y divide-gray-200 text-sm w-max">
            <thead class="bg-gray-100">
                <tr>
                    {#each formColumnsDisplay as col}
                        {#if col.key === "issue_number"}
                            <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;"
                                on:click={() => toggleSort(col.key)}
                            >
                                {col.title}
                                {#if sortColumn === col.key}
                                {sortOrder === 'asc' ? ' 🔼' : ' 🔽'}
                                {/if}
                            </th>
                        {:else}
                            <th
                                class="px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
                                on:click={() => toggleSort(col.key)}
                            >
                                {col.title}
                                {#if sortColumn === col.key}
                                {sortOrder === 'asc' ? ' 🔼' : ' 🔽'}
                                {/if}
                            </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 formColumnsDisplay as col}
                            {#if col.key === "issue_number"}
                                <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">
                                    {#if projectIssueMap.has(row.id) || purchaseOrderMap.has(row.id)}
                                    <button
                                        class="text-gray-400 cursor-not-allowed"
                                        disabled
                                        title="Cannot edit: linked to a {projectIssueMap.has(row.id) ? 'project' : 'purchase order'}"
                                    >
                                        ✏️ Edit
                                    </button>
                                    <button
                                        class="text-gray-400 cursor-not-allowed"
                                        disabled
                                        title="Cannot delete: linked to a {projectIssueMap.has(row.id) ? 'project' : 'purchase order'}"
                                    >
                                        🗑️ Delete
                                    </button>
                                {:else}
                                    <button
                                        class="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-blue-700"
                                        on:click={() => openModal(row)}
                                    >
                                        ✏️ Edit
                                    </button>
                                    <button
                                        class="inline-flex items-center gap-1 rounded bg-red-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-red-700"
                                        on:click={() => deleteIssue(row.id)}
                                    >
                                        🗑️ Delete
                                    </button>
                                {/if}
                                </td>
                            {:else if col.key === "move_issue"}
                                {#if row[col.key as keyof Issue] === "PROJECT"}
                                <td class="px-4 py-2">
                                    <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
                                    >
                                        ➡️ PROJECT
                                    </button>
                                </td>
                            {:else if row[col.key as keyof Issue] === "PURCHASE_ORDER"}
                                <td class="px-4 py-2">
                                    <button
                                        class="inline-flex items-center gap-1 rounded bg-yellow-600 px-3 py-1.5 text-white text-xs font-medium hover:bg-yellow-700"
                                        disabled
                                    >
                                        ➡️ PURCHASE ORDER
                                    </button>
                                </td>
                            {:else}
                                <td class="px-4 py-2 flex gap-2">
                                    {#if projectIssueMap.has(row.id)}
                                        <!-- Project already exists -->
                                        <button
                                            class="bg-green-400 text-white px-3 py-1.5 rounded text-xs font-medium cursor-not-allowed"
                                            disabled
                                            title="Already linked to a project"
                                        >
                                            ✔ LINKED PROJECT
                                        </button>
                                    {:else}
                                        <button
                                            class="bg-green-600 text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-green-700"
                                            on:click={() => openProjectModal(row)}
                                            disabled={purchaseOrderMap.has(row.id)} 
                                            title={purchaseOrderMap.has(row.id) ? "Disabled: already in purchase order" : ""}
                                        >
                                            ➡️ PROJECT
                                        </button>
                                    {/if}
                                
                                    {#if purchaseOrderMap.has(row.id)}
                                        <!-- PO already exists -->
                                        <button
                                            class="bg-yellow-400 text-white px-3 py-1.5 rounded text-xs font-medium cursor-not-allowed"
                                            disabled
                                            title="Already linked to a purchase order"
                                        >
                                            ✔ LINKED PO
                                        </button>
                                    {:else}
                                        <button
                                            class="bg-yellow-600 text-white px-3 py-1.5 rounded text-xs font-medium hover:bg-yellow-700"
                                            on:click={() => openPurchaseOrderModal(row)}
                                            disabled={projectIssueMap.has(row.id)}
                                            title={projectIssueMap.has(row.id) ? "Disabled: already in project" : ""}
                                        >
                                            ➡️ PURCHASE ORDER
                                        </button>
                                    {/if}
                                </td>
                            {/if}
                        
                            {:else if col.key === "guest_has_aggreed_issue_has_been_resolved"}
                                <td class="px-4 py-2">
                                    {#if row[col.key as keyof Issue]}
                                        ✅
                                    {:else}
                                        ❌
                                    {/if}
                                </td>
                            {:else if col.key === "status"}
                                <td class="px-4 py-2">
                                    {#if row[col.key as keyof Issue]}
                                        <span class="text-green-600 font-semibold"
                                            >✅ RESOLVED</span
                                        >
                                    {:else}
                                        <span class="text-blue-600 font-semibold"
                                            >⏳ ONPROGRESS</span
                                        >
                                    {/if}
                                </td>
                            {:else if col.key === "issue_related_image"}
                                <td class="px-4 py-2">
                                    {#if typeof row[col.key as keyof Issue] === "string" && row[col.key as keyof Issue]}
                                        {#await getPublicUrl(row[col.key as keyof Issue] as string) 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 === "url_drive"}
                                <td class="px-4 py-2">
                                    {#if typeof row[col.key as keyof Issue] === "string" && row[col.key as keyof Issue]}
                                        <a
                                            href={row[col.key as keyof Issue] as string}
                                            target="_blank"
                                            class="text-blue-600 hover:underline"
                                            >View Drive Link</a
                                        >
                                    {:else}
                                        No Drive Link
                                    {/if}
                                </td>
                            {:else if col.key === "reported_date"}
                                <td class="px-4 py-2">
                                    {typeof row[col.key as keyof Issue] ===
                                        "string" ||
                                    typeof row[col.key as keyof Issue] ===
                                        "number"
                                        ? new Date(
                                              row[col.key as keyof Issue] as
                                                  | string
                                                  | number,
                                          ).toLocaleString("en-US")
                                        : ""}
                                </td>
                            {:else if col.key === "need_approval"}
                                <td class="px-4 py-2">
                                    {#if row[col.key as keyof Issue]}
                                        ✅
                                    {:else}
                                        ❌
                                    {/if}
                                </td>
                            {:else if col.key === "follow_up"}
                                <td class="px-4 py-2">
                                    {#if row[col.key as keyof Issue]}
                                        ✅
                                    {:else}
                                        ❌
                                    {/if}
                                </td>
                            {:else if col.key === "created_at"}
                                <!-- beri jam jg -->
                                <td class="px-4 py-2">
                                    {new Date(
                                        row[col.key as keyof Issue] as string,
                                    ).toLocaleString("en-US")}
                                </td>
                            {:else if col.key === "updated_at"}
                                <td class="px-4 py-2">
                                    {row[col.key as keyof Issue]
                                        ? new Date(
                                              row[
                                                  col.key as keyof Issue
                                              ] as string,
                                          ).toLocaleString("en-US")
                                        : ""}
                                </td>
                            {:else}
                                <td class="px-4 py-2 text-gray-700"
                                    >{row[col.key as keyof Issue]}</td
                                >
                            {/if}
                        {/each}
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>

    <!-- Pagination controls -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2 text-sm">
        <!-- Left: Showing X–Y of Z -->
        <div>
          Showing {(currentPage - 1) * rowsPerPage + 1}–
          {Math.min(currentPage * rowsPerPage, filteredRows.length)}
          of {filteredRows.length}
        </div>
      
        <!-- Right: Rows per page & Pagination -->
        <div class="flex items-center space-x-2">
          <label class="text-gray-600">Rows per page:</label>
          <select
            bind:value={rowsPerPage}
            class="border px-2 py-1 rounded"
            on:change={() => {
              currentPage = 1; // Reset to first page when changing page size
            }}
          >
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
      
          <Pagination {totalPages} {currentPage} {goToPage} />
        </div>
    </div>
</div>

<!-- Modal -->
{#if showModal}
    <div
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
        <form
            on:submit|preventDefault={saveIssue}
            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">
                {isEditing ? "Edit Issue" : "Add New Issue"}
            </h3>
            {#each formColumns as col}
                {#if col.key === "name"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Customer / Guest Name
                            <input
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'name',
                                )}"
                                name="name"
                                type="text"
                                bind:value={newIssue[col.key as keyof Issue]}
                                placeholder={col.title}
                                required
                            />
                            {#if $formErrors.name}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.name}
                                </p>
                            {/if}
                        </label>
                    </div>
                {:else if col.key === "issue_related_image"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Issue Related Image
                            <input
                                name="issue_related_image"
                                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 newIssue.issue_related_image}
                                {#await getPublicUrl(newIssue.issue_related_image) then url}
                                    <img
                                        src={url}
                                        alt="Preview"
                                        class="mt-2 max-h-48 rounded border"
                                    />
                                {/await}
                            {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "reported_date"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Reported Date
                            <input
                                name="reported_date"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'reported_date',
                                )}"
                                type="date"
                                bind:value={newIssue[col.key as keyof Issue]}
                            />
                            {#if $formErrors.reported_date}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.reported_date}
                                </p>
                            {/if}
                        </label>
                    </div>
                {:else if col.key === "need_approval"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Need Approval
                            <input
                            type="checkbox"
                            bind:checked={newIssue.need_approval}
                            class="form-checkbox"
                            />
                        </label>
                        <p class="text-sm text-gray-500 ml-1">
                            {newIssue.need_approval
                                ? "✅ Approval Required"
                                : "❌ No Approval Needed"}
                        </p>
                    </div>
                {:else if col.key === "issue_source"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Issue Source
                            <select
                                name="issue_source"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'issue_source',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected
                                    >Select Source</option
                                >
                                {#each issueSource as source}
                                    <option value={source.value}
                                        >{source.label}</option
                                    >
                                {/each}
                            </select>
                            {#if $formErrors.issue_source}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.issue_source}
                                </p>
                            {/if}
                        </label>
                    </div>
                {:else if col.key === "reported_by"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Reported By
                            <select
                                name="reported_by"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'reported_by',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected >Select Reporter</option>
                                {#each dataUser as reporter}
                                    <option value={reporter.id}>{reporter.employee_name}</option>
                                {/each}
                            </select>
                            {#if $formErrors.reported_by}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.reported_by}
                                </p>
                            {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "input_by"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Input By
                            <select
                                name="input_by"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'input_by',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected
                                    >Select Input By</option
                                >
                                {#each dataUser as input}
                                    <option value={input.id}
                                        >{input.employee_name}</option
                                    >
                                {/each}
                            </select>
                            {#if $formErrors.input_by}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.input_by}
                                </p>
                            {/if}
                        </label>
                    </div>
                {:else if col.key === "area_of_villa"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Area of Villa
                            <select
                                name="area_of_villa"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'area_of_villa',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected
                                    >Select Area</option
                                >
                                {#each areaOfVilla as area}
                                    <option value={area.value}>{area.label}</option>
                                {/each}
                            </select>
                            {#if $formErrors.area_of_villa}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.area_of_villa}
                                </p>
                            {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "issue_type"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Issue Type
                            <select
                                name="issue_type"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'issue_type',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected
                                    >Select Issue Type</option
                                >
                                {#each issueTypes as type}
                                    <option value={type.value}>{type.label}</option>
                                {/each}
                            </select>
                            {#if $formErrors.issue_type}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.issue_type}
                                </p>
                            {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "priority"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >Priority
                            <select
                                name="priority"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'priority',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                            >
                                <option value="" disabled selected
                                    >Select Priority</option
                                >
                                {#each priority as p}
                                    <option value={p.value}>{p.label}</option>
                                {/each}
                            </select>
                            {#if $formErrors.priority}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.priority}
                                </p>
                            {/if}
                            </label>
                    </div>
                {:else if col.key === "villa_id"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Villa Name
                            <select
                            name="villa_id"
                            class="w-full border px-3 py-2 rounded {errorClass(
                                'villa_id',
                            )}"
                            bind:value={newIssue[col.key as keyof Issue]}
                        >
                            <option value="" disabled selected
                                >Select Villa</option
                            >
                            {#each dataVilla as villa}
                                <option value={villa.id}
                                    >{villa.villa_name}</option
                                >
                            {/each}
                        </select>
                        {#if $formErrors.villa_id}
                            <p class="text-red-500 text-xs">
                                {$formErrors.villa_id}
                            </p>
                        {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "description_of_the_issue"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Description of The Issue
                            <textarea
                                name="description_of_the_issue"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'description_of_the_issue',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                                placeholder={col.title}
                                rows="4"
                            ></textarea>
                            {#if $formErrors.description_of_the_issue}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.description_of_the_issue}
                                </p>
                            {/if}
                        </label>
                        
                    </div>
                {:else if col.key === "status"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700">
                            Status
                            <select
                                name="status"
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    'status',
                                )}"
                                bind:value={newIssue[col.key as keyof Issue]}
                                placeholder={col.title}
                            >
                                <option value="" disabled selected
                                    >Select Status</option
                                >
                                <option value="true">Done</option>
                                <option value="false">On Progress</option>
                            </select>
                            {#if $formErrors.status}
                                <p class="text-red-500 text-xs">
                                    {$formErrors.status}
                                </p>
                            {/if}
                        </label>
                    </div>  
                {:else}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}
                            <input
                            name={col.key}
                            class="w-full border px-3 py-2 rounded"
                            type="text"
                            bind:value={newIssue[col.key as keyof Issue]}
                            placeholder={col.title}
                        />
                        </label>
                        
                    </div>
                {/if}
            {/each}
            <div class="flex justify-end gap-2 mt-4">
                <button
                    class="px-4 py-2 text-sm rounded bg-gray-200 hover:bg-gray-300"
                    on:click={() => (
                        (showModal = false),
                        (newIssue = {}),
                        (selectedFile = null),
                        (imagePreviewUrl = null)
                    )}
                >
                    Cancel
                </button>
                <button
                    class="px-4 py-2 text-sm rounded bg-blue-600 text-white hover:bg-blue-700"
                    type="submit"
                >
                    Save
                </button>
            </div>
        </form>
    </div>
{/if}
{#if showProjectModal}
<div class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
    <form
        on:submit|preventDefault={submitProject}
        class="bg-white p-6 rounded shadow-lg w-[600px] max-h-[90vh] overflow-y-auto space-y-4"
    >
        <h2 class="text-lg font-semibold">Create Project from Issue</h2>

        {#if selectedIssueSummary}
            <div class="text-sm text-gray-600 italic mb-2">
                Related Issue: “{selectedIssueSummary}”
            </div>
        {/if}

        <label class="block text-sm font-medium text-gray-700">
            Project Name *
            <input
                type="text"
                bind:value={newProject.project_name}
                class="w-full border px-3 py-2 rounded"
                required
            />
        </label>

        <label class="block text-sm font-medium text-gray-700">
            Assigned To
            <select bind:value={newProject.assigned_to} class="w-full border px-3 py-2 rounded">
                <option value="">-- Select Employee --</option>
                {#each dataUser as emp}
                    <option value={emp.id}>{emp.employee_name}</option>
                {/each}
            </select>
        </label>

        <label class="block text-sm font-medium text-gray-700">
            Input By
            <select bind:value={newProject.input_by} class="w-full border px-3 py-2 rounded">
                <option value="">-- Select Employee --</option>
                {#each dataUser as emp}
                    <option value={emp.id}>{emp.employee_name}</option>
                {/each}
            </select>
        </label>

        <label class="block text-sm font-medium text-gray-700">
            Project Due Date
            <input
                type="date"
                bind:value={newProject.project_due_date}
                class="w-full border px-3 py-2 rounded"
            />
        </label>

        <label class="block text-sm font-medium text-gray-700">
            Comment
            <textarea
                bind:value={newProject.project_comment}
                class="w-full border px-3 py-2 rounded"
                rows="2"
            ></textarea>
        </label>

        <div class="flex justify-end gap-2">
            <button
                type="button"
                class="px-4 py-2 text-sm rounded bg-gray-300 text-black hover:bg-gray-400"
                on:click={() => showProjectModal = false}
            >
                Cancel
            </button>
            <button
                type="submit"
                class="px-4 py-2 text-sm rounded bg-blue-600 text-white hover:bg-blue-700"
            >
                Submit
            </button>
        </div>
    </form>
</div>
{/if}
{#if showPurchaseOrderModal}
<div class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
    <form on:submit|preventDefault={submitPurchaseOrder}
          class="bg-white p-6 rounded shadow-lg w-[600px] max-h-[90vh] overflow-y-auto space-y-4">
        <h2 class="text-lg font-semibold">Create Purchase Order</h2>

        <p class="text-sm text-gray-600 italic">Related Issue: “{selectedIssueSummary}”</p>

        <label class="block">
            Requester *
            <select bind:value={newPO.requested_by} class="input w-full">
                <option value="">-- Select Employee --</option>
                {#each dataUser as emp}
                    <option value={emp.id}>{emp.employee_name}</option>
                {/each}
            </select>
        </label>

        <label class="block">
            Type *
            <select bind:value={newPO.po_type} class="input w-full">
                <option value="">-- Select Type --</option>
                <option value="project">Project</option>
                <option value="purchase">Purchase</option>
                <option value="repair">Repair</option>
            </select>
        </label>

        <label class="block">
            Request Date
            <input type="date" bind:value={newPO.requested_date} class="input w-full" />
        </label>

        <label class="block">
            PO Due Date
            <input type="date" bind:value={newPO.po_due} class="input w-full" />
        </label>

        <div class="flex justify-end gap-2">
            <button type="button" class="btn" on:click={() => showPurchaseOrderModal = false}>Cancel</button>
            <button type="submit" class="btn-primary">Submit</button>
        </div>
    </form>
</div>
{/if}
