<script lang="ts">
    // This is a placeholder for any script you might want to add
    // For example, you could handle form submission here
    import { onMount } from "svelte";
    import { supabase } from "$lib/supabaseClient";
    import logo from "$lib/images/logo.webp";

    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" }
    ];
    //InputBy & reportedBy should dropdown data from active employee, from table vb_employee (field employee_name and employee_status = 'Active')

    const followUp = [
        { label: "Communication Needed by Reservation", value: "true" },
        { label: "Communication Completed", value: "false" },
    ];

    let dataUser: { id: string; employee_name: string }[] = [];
    let dataVilla: { id: string; villa_name: string }[] = [];
    let issueImageFile: File | null = null;
    let issueImageUrl: string = "";
    let isSubmitting = false;

    function handleFileChange(event: Event): void {
        const target = event.target as HTMLInputElement;
        if (target.files && target.files.length > 0) {
            const file = target.files[0];
            if (
                !["image/jpeg", "image/png", "image/webp"].includes(file.type)
            ) {
                alert("Only JPG, PNG, or WEBP images are allowed.");
                return;
            }
            if (file.size > 2 * 1024 * 1024) {
                alert("Image must be less than 2MB.");
                return;
            }
            issueImageFile = file;
            issueImageUrl = URL.createObjectURL(file);
        }
    }

    onMount(async () => {
        // Fetch active villas
        const { data: villaData, error: villaError } = await supabase
            .from("vb_villas")
            .select("id, villa_name")
            .eq("villa_status", "Active");

        if (villaError) {
            console.error("Error fetching villas:", villaError);
        } else {
            dataVilla = villaData || [];
        }

        // Fetch active employees
        const { data: userData, error: userError } = await supabase
            .from("vb_employee")
            .select("id, employee_name")
            .eq("employee_status", "Active");

        if (userError) {
            console.error("Error fetching employees:", userError);
        } else {
            dataUser = userData || [];
        }
    });

    async function handleSubmit(event: Event): Promise<void> {
        event.preventDefault();
        isSubmitting = true;

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

            if (issueImageFile) {
                const filePath = `issues/${Date.now()}_${issueImageFile.name}`;

                const { data, error } = await supabase.storage
                    .from("villabugis")
                    .upload(filePath, issueImageFile);

                if (error) {
                    alert("Image upload failed");
                    console.error(error);
                    return;
                }

                const { data: publicData } = supabase.storage
                    .from("villabugis")
                    .getPublicUrl(filePath);

                issueImageUrl = publicData.publicUrl;
            }

            const issue_number = await generateIssueNumber();

            const issue = {
                issue_number,
                description_of_the_issue: formData.get("description_of_the_issue") as string,
                villa_id: formData.get("villa_name") 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,
                issue_source: formData.get("issue_source") as string,
                reported_date: formData.get("reported_date") as string,
                reported_by: formData.get("reported_by") as string,
                input_by: formData.get("input_by") as string,
                resolution: formData.get("resloution") as string,
                guest_has_aggreed_issue_has_been_resolved: formData.get(
                    "guest_has_aggreed_issue_has_been_resolved",
                ) as string,
                follow_up: formData.get("follow_up") as string,
                guest_communication: formData.get(
                    "guest_communication",
                ) as string,
                issue_related_image: issueImageUrl,
                url_drive: formData.get("url_drive") as string,
                created_at: new Date().toISOString(),
            };

            // Insert into Supabase
            const { error } = await supabase.from("vb_issues").insert([issue]);

            if (error) {
                alert("Error submitting issue");
                console.error(error);
                return;
            }

            // POST to webhook
            await fetch("https://flow.catalis.app/webhook/vb-issuecreate", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(issue),
            });

            alert("Issue submitted successfully!");
            (event.target as HTMLFormElement).reset();
            issueImageUrl = "";
            issueImageFile = null;
        } catch (err) {
            alert("Unexpected error");
            console.error(err);
        } finally {
            isSubmitting = false;
        }
    }

    async function generateIssueNumber(): Promise<string> {
        const { data } = await supabase
            .from("vb_issues")
            .select("issue_number")
            .order("created_at", { ascending: false })
            .limit(1);

        if (!data || data.length === 0) {
            return "ISS-000500";
        }

        const last = data[0].issue_number?.split("-")[1] || "500";
        const nextNumber = parseInt(last, 10) + 1;
        return `ISS-${nextNumber.toString().padStart(6, "0")}`;
    }
</script>

<div>
    <form
        class="max-w-6xl mx-auto bg-white p-8 rounded-2xl shadow-xl space-y-8 text-gray-800"
        on:submit|preventDefault={handleSubmit}
    >
        <!-- logo -->
        <div class="text-center mb-6">
            <img
                src={logo}
                alt="Logo"
                class="mx-auto"
                loading="lazy"
                width="250"
            />
        </div>
        <!-- Title -->
        <h2 class="text-2xl font-semibold text-center">Submit New Issue</h2>

        <!-- 2 Column Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <!-- Left Column -->
            <div class="space-y-5">
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Description of Issues<span class="text-red-500">*</span>
                        <input
                            name="description_of_the_issue"
                            type="text"
                            placeholder="Tell detail of the issue"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                            required
                        />
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Issue Source
                        <span class="text-red-500">*</span>
                        <select
                            name="issue_source"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each issueSource as source}
                                <option value={source.value}
                                    >{source.label}</option
                                >
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Villa Name
                        <span class="text-red-500">*</span>
                        <select
                            name="villa_name"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each dataVilla as villa}
                                <option value={villa.id}
                                    >{villa.villa_name}</option
                                >
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Issue related image
                        <div
                            class="w-full border-2 border-dashed rounded-xl px-4 py-10 text-center text-gray-400 cursor-pointer hover:bg-gray-50 transition relative"
                        >
                            <input
                                name="issue_related_image"
                                type="file"
                                accept="image/*"
                                class="hidden"
                                id="issue_image"
                                on:change={handleFileChange}
                            />
                            <label for="issue_image" class="cursor-pointer">
                                <span class="block mb-2">Click to upload</span>
                                <span class="text-xs">or drag and drop</span>
                            </label>

                            <p class="mt-2 text-xs">
                                Supported formats: JPG, PNG, GIF
                            </p>
                        </div>
                        {#if issueImageUrl}
                            <div class="mt-4">
                                <p class="text-sm text-gray-600 mb-2">
                                    Preview:
                                </p>
                                <img
                                    src={issueImageUrl}
                                    alt="Issue preview"
                                    class="w-full h-48 object-cover rounded-xl shadow-sm"
                                />
                            </div>
                        {/if}
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Date Reported
                        <span class="text-red-500">*</span>
                        <input
                            name="reported_date"
                            type="date"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                            required
                        />
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Reported By
                        <span class="text-red-500">*</span>
                        <select
                            name="reported_by"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each dataUser as reporter}
                                <option value={reporter.id}>
                                    {reporter.employee_name}
                                </option>
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >URLDrive
                        <input
                            name="url_drive"
                            type="url"
                            placeholder="Enter URL"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                        />
                    </label>
                </div>
            </div>
            <!-- Right Column -->
            <div class="space-y-5">
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Priority
                        <span class="text-red-500">*</span>
                        <select
                            name="priority"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each priority as p}
                                <option value={p.value}>{p.label}</option>
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Issue Type<span class="text-red-500">*</span>
                        <select
                            name="issue_type"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each issueTypes as type}
                                <option value={type.value}>{type.label}</option>
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Area of Villa<span class="text-red-500">*</span>
                        <select
                            name="area_of_villa"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each areaOfVilla as area}
                                <option value={area.value}>{area.label}</option>
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Customer / Guest Name
                        <input
                            name="name"
                            type="text"
                            placeholder="Enter text"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                        />
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Due Issue Date<span class="text-red-500">*</span>
                        <input
                            name="due_issue_date"
                            type="date"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                        />
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Input By<span class="text-red-500">*</span>
                        <select
                            name="input_by"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                            required
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each dataUser as input}
                                <option value={input.id}
                                    >{input.employee_name}</option
                                >
                            {/each}
                        </select>
                    </label>
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1">
                        Follow Up
                        <select
                            name="follow_up"
                            class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600"
                        >
                            <option value="" disabled selected
                                >Select option...</option
                            >
                            {#each followUp as follow}
                                <option value={follow.value}
                                    >{follow.label}</option
                                >
                            {/each}
                        </select>
                    </label>
                </div>
            </div>
        </div>

        <!-- Full Width Fields -->
        <div class="space-y-6">
            <div>
                <label class="block text-sm font-medium mb-1">
                    Resolved How?
                    <textarea
                        name="resolution"
                        rows="3"
                        placeholder="How you resolve? e.g. 'copy to project'"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                    ></textarea>
                </label>
            </div>
            <div>
                <label class="block text-sm font-medium mb-1">
                    Guest Communication
                    <textarea
                        name="guest_communication"
                        rows="3"
                        placeholder="Communication with guest while still in the villa"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400"
                    ></textarea>
                </label>
            </div>
            <div class="flex items-center space-x-2">
                <label class="text-sm"
                    >Guest has agreed issue has been resolved
                    <input
                        name="guest_has_aggreed_issue_has_been_resolved"
                        value="false"
                        type="checkbox"
                        class="h-4 w-4 rounded border-gray-300"
                    />
                </label>
            </div>
        </div>

        <!-- Submit Button -->
        <div class="text-center pt-4">
            <button
                type="submit"
                class="bg-purple-600 text-white px-8 py-3 rounded-xl hover:bg-purple-700 transition-all font-medium shadow-md"
                disabled={isSubmitting}
            >
                {isSubmitting ? "Submitting..." : "Submit"}
            </button>
        </div>
    </form>
</div>
