<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 { writable } from "svelte/store";

    type TimesheetsInsert = {
        name: string;
        staff_id: string;
        date_in: Date;
        date_out: Date;
        type_of_work: string;
        category_of_work: string;
        approval: string;
        villa_id: string;
        approved_by: string;
        approved_date: Date;
        total_hours_work: number;
        remarks: string;
        vacant: boolean;
    };

    type Timesheets = {
        id: string;
        name: string;
        staff_id: string;
        date_in: Date;
        date_out: Date;
        type_of_work: string;
        category_of_work: string;
        approval: string;
        villa_id: string;
        approved_by: string;
        approved_date: Date;
        total_hours_work: number;
        remarks: string;
        vacant: boolean;
        created_at?: Date;
    };

    const categoryOfWork = [
        { label: "Cleaning", value: "Cleaning" },
        { label: "Gardening/Pool", value: "Gardening/Pool" },
        { label: "Maintenance", value: "Maintenance" },
        { label: "Security", value: "Security" },
        { label: "Other", value: "Other" },
    ];

    const typeOfWork = [
        { label: "Running", value: "Running" },
        { label: "Periodic", value: "Periodic" },
        { label: "Irregular", value: "Irregular" },
    ];

    const reportedBy = [
        { label: "Admin", value: "Admin" },
        { label: "Staff", value: "Staff" },
        { label: "Manager", value: "Manager" },
        { label: "Guest", value: "Guest" },
    ];

    type Villa = {
        id: string;
        name: string;
    };

    let dataVilla: Villa[] = [];

    onMount(async () => {
        const { data, error } = await supabase
            .from("villas")
            .select("id, name");

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

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

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

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

        const timesheets: TimesheetsInsert = {
            name: formData.get("name") as string,
            staff_id: formData.get("staff_id") as string,
            date_in: new Date(formData.get("date_in") as string),
            date_out: new Date(formData.get("date_out") as string),
            type_of_work: formData.get("type_of_work") as string,
            category_of_work: formData.get("category_of_work") as string,
            approval: formData.get("approval") as string,
            villa_id: formData.get("villa_id") as string,
            approved_by: formData.get("approved_by") as string,
            approved_date: new Date(formData.get("approved_date") as string),
            // total_hours_work can be calculated based on date_in and date_out
            total_hours_work:
                Math.abs(
                    new Date(formData.get("date_in") as string).getTime() -
                        new Date(formData.get("date_out") as string).getTime(),
                ) /
                (1000 * 60 * 60), // Convert milliseconds to hours
            remarks: formData.get("remarks") as string,
            vacant: formData.get("vacant") === "false" ? false : true,
        };

        const { data, error } = await supabase
            .from("timesheets")
            .insert([timesheets]);

        if (error) {
            console.error("Error submitting timesheets:", error);
        } else {
            console.log("Timesheets submitted successfully:", data);
            alert("Timesheets submitted successfully!");
        }
    }

    export let formErrors = writable<{ [key: string]: string }>({});

    function validateForm(formData: FormData): boolean {
        const errors: { [key: string]: string } = {};
        const requiredFields = [
            "name",
            "type_of_work",
            "villa_id",
            "date_out",
            "reported_by",
            "category_of_work",
            "date_in",
        ];

        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 errorClass(field: string): string {
        return $formErrors[field] ? "border-red-500" : "border";
    }
</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}
    >
        <!-- Title -->
        <h2 class="text-2xl font-semibold">Timesheet Form</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"
                        >Work Description<span class="text-red-500">*</span><br
                        />
                        <span class="text-xs text-gray-500"
                            >Enter detail of work</span
                        >
                    </label>
                    <input
                        name="name"
                        type="text"
                        placeholder="Tell detail of work"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 {errorClass(
                            'name',
                        )}"
                    />
                    {#if $formErrors.name}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.name}
                        </p>
                    {/if}
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Type of Work<span class="text-red-500">*</span></label
                    >
                    <select
                        name="type_of_work"
                        class={`w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600 ${errorClass("type_of_work")}`}
                    >
                        <option value="" disabled selected
                            >Select option...</option
                        >
                        {#each typeOfWork as source}
                            <option value={source.value}>{source.label}</option>
                        {/each}
                    </select>
                    {#if $formErrors.type_of_work}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.type_of_work}
                        </p>
                    {/if}
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Villa Name<span class="text-red-500">*</span></label
                    >
                    <select
                        name="villa_id"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600 {errorClass(
                            'villa_name',
                        )}"
                    >
                        <option value="" disabled selected
                            >Select option...</option
                        >
                        {#each dataVilla as villa}
                            <option value={villa.id}>{villa.name}</option>
                        {/each}
                    </select>
                    {#if $formErrors.villa_id}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.villa_id}
                        </p>
                    {/if}
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Date / Time Out<span class="text-red-500">*</span
                        ></label
                    >
                    <!-- date and time -->
                    <input
                        name="date_out"
                        type="datetime-local"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 {errorClass(
                            'Date / Time Out',
                        )}"
                    />
                    {#if $formErrors.date_out}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.date_out}
                        </p>
                    {/if}
                </div>
            </div>

            <!-- Right Column -->
            <div class="space-y-5">
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Reported By<span class="text-red-500">*</span>
                        <br />
                        <span class="text-xs text-gray-500"
                            >Who reported this issue?</span
                        >
                    </label>
                    <select
                        name="reported_by"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 text-gray-600 {errorClass(
                            'reported_by',
                        )}"
                    >
                        <option value="" disabled selected
                            >Select option...</option
                        >
                        {#each reportedBy as reporter}
                            <option value={reporter.value}>
                                {reporter.label}
                            </option>
                        {/each}
                    </select>
                    {#if $formErrors.reported_by}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.reported_by}
                        </p>
                    {/if}
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Category of Work<span class="text-red-500">*</span
                        ></label
                    >
                    <select
                        name="category_of_work"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 text-gray-600 {errorClass(
                            'Category of Work',
                        )}"
                    >
                        <option value="" disabled selected
                            >Select option...</option
                        >
                        {#each categoryOfWork as p}
                            <option value={p.value}>{p.label}</option>
                        {/each}
                    </select>
                    {#if $formErrors.category_of_work}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.category_of_work}
                        </p>
                    {/if}
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1"
                        >Date / Time In<span class="text-red-500">*</span
                        ></label
                    >
                    <input
                        name="date_in"
                        type="datetime-local"
                        class="w-full border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-purple-400 {errorClass(
                            'Date / Time In',
                        )}"
                    />
                    {#if $formErrors.date_in}
                        <p class="text-sm text-red-500 mt-1">
                            {$formErrors.date_in}
                        </p>
                    {/if}
                </div>
            </div>
        </div>

        <!-- Full Width Fields -->
        <div class="space-y-6">
            <div>
                <label class="block text-sm font-medium mb-1">Remarks</label>
                <textarea
                    name="remarks"
                    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>
            </div>
            <div class="flex items-center space-x-2">
                <input
                    name="vacant"
                    value="false"
                    type="checkbox"
                    id="guest_agreed"
                    class="h-4 w-4 rounded border-gray-300"
                />
                <label for="guest_agreed" class="text-sm">Vacant</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"
            >
                Submit
            </button>
        </div>
    </form>
</div>
