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

    type Villa = {
        id: string;
        villa_name: string;
        villa_manager: string;
        villa_location: string;
        villa_status: string;
        no_of_bedrooms: number;
        closeable_living_room: boolean;
        villa_condition: string;
        monthly_rental_pre_approved_status: boolean;
        long_term_rental_pre_approval: boolean;
        pet_allowed_pre_approval_status: boolean;
        season_1_rate: number;
        season_2_rate: number;
        season_3_rate: number;
        season_4_rate: number;
        season_5_rate: number;
        season_6_rate: number;
        season_7_rate: number;
        villa_email_address: string;
        villa_recovery_email_adress: string;
        owner_portal_username: string;
        owner_portal_password: string;
        created_by: string;
        created_at: string;
    };

    let allRows: Villa[] = [];
    let offset = 0;
    let limit = 10;
    let totalItems = 0;
    export let formErrors = writable<{ [key: string]: string }>({});

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

    const columns: columns[] = [
        { key: "villa_name", title: "Villa Name" },
        { key: "villa_manager", title: "Villa Manager" },
        { key: "villa_location", title: "Villa Location" },
        { key: "villa_status", title: "Villa Status" },
        { key: "no_of_bedrooms", title: "No Of Bedrooms" },
        { key: "closeable_living_room", title: "Closeable Living Room" },
        { key: "villa_condition", title: "Villa Condition" },
        {
            key: "monthly_rental_pre_approved_status",
            title: "Monthly Rental Pre Approved Status",
        },
        {
            key: "long_term_rental_pre_approval",
            title: "Long Term Rental Pre Approval",
        },
        {
            key: "pet_allowed_pre_approval_status",
            title: "Pet Allowed Pre Approval Status",
        },
        { key: "season_1_rate", title: "Season 1 Rate" },
        { key: "season_2_rate", title: "Season 2 Rate" },
        { key: "season_3_rate", title: "Season 3 Rate" },
        { key: "season_4_rate", title: "Season 4 Rate" },
        { key: "season_5_rate", title: "Season 5 Rate" },
        { key: "season_6_rate", title: "Season 6 Rate" },
        { key: "season_7_rate", title: "Season 7 Rate" },
        { key: "villa_email_address", title: "Villa Email Address" },
        {
            key: "villa_recovery_email_adress",
            title: "Villa Recovery Email Address",
        },
        { key: "owner_portal_username", title: "Owner Portal Username" },
        { key: "owner_portal_password", title: "Owner Portal Password" },
        { key: "created_by", title: "Created By" },
        { key: "created_at", title: "Created At" },
        { key: "actions", title: "Actions" },
    ];

    async function fetchVillas(
        filter: string | null = null,
        sort: string | null = null,
        order: "asc" | "desc" = "desc",
        limit: number | null = null,
        offset: number | null = null,
    ) {
        let query = supabase.from("vb_villas").select("*");

        if (filter) {
            query = query.ilike("villa_name", `%${filter}%`);
        }

        if (sort) {
            query = query.order(sort, { ascending: order === "asc" });
        }

        if (limit !== null && offset !== null) {
            query = query.range(offset, offset + limit - 1);
        } else if (limit !== null) {
            query = query.limit(limit);
        }

        const { data, error } = await query;

        console.log("Fetched villas:", data);

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

        allRows = data.map((villa) => ({
            ...villa,
            villa_condition: villa.villa_condition || "",
            villa_status: villa.villa_status || "",
            created_at: new Date(villa.created_at).toISOString(),
        })) as Villa[];

        // count the total number of rows
        const { count, error: countError } = await supabase
            .from("vb_villas")
            .select("*", { count: "exact" })
            .ilike("villa_name", filter ? `%${filter}%` : "%");

        if (countError) {
            console.error("Error counting villas:", countError);
            return;
        }
        console.log("Total villas count:", count);

        totalItems = count || 0;
        offset = offset || 0; // Ensure offset is set to 0 if not provided
    }

    onMount(() => {
        fetchVillas(null, "created_at", "desc", 10, 0);
    });

    let currentPage = offset + 1; // Start at page 1
    let rowsPerPage = limit || 10; // Default to 10 rows per page
    $: totalPages = Math.ceil(totalItems / rowsPerPage);

    function goToPage(page: number) {
        if (page >= 1 && page <= totalPages) currentPage = page;
        offset = (currentPage - 1) * rowsPerPage;
        fetchVillas(null, "created_at", "desc", rowsPerPage, offset);
        console.log(`Fetching page ${currentPage} with offset ${offset}`);
    }

    // Modal Logic
    let showModal = false;
    let isEditing = false;
    let currentEditingId: string | null = null;
    let newVilla: Record<string, any> = {};
    const excludedKeys = ["id", "created_at", "created_by", "actions"];
    $: formColumns = columns.filter((col) => !excludedKeys.includes(col.key));

    function openModal(villa?: Villa) {
        showModal = true;
        isEditing = !!villa;
        currentEditingId = villa?.id ?? null;
        newVilla = {};
        for (const col of formColumns) {
            newVilla[col.key] = villa
                ? (villa[col.key as keyof Villa] ?? "")
                : "";
        }
    }

    //validation function
    function validateForm(formData: FormData): boolean {
        // Basic validation: check if required fields are filled
        const errors: { [key: string]: string } = {};
        const requiredFields = [
            "villa_name",
            //            "villa_manager",
            //            "villa_location",
            "villa_status",
            "no_of_bedrooms",
            //            "villa_condition",
            //           "season_1_rate",
            //            "season_2_rate",
            //            "season_3_rate",
            //            "season_4_rate",
            //            "season_5_rate",
            //            "season_6_rate",
            //            "season_7_rate",
            //            "villa_email_address",
            //            "owner_portal_username",
            //            "owner_portal_password",
            //            "closeable_living_room",
            //            "monthly_rental_pre_approved_status",
            //            "long_term_rental_pre_approval",
            //            "pet_allowed_pre_approval_status",
            //            "villa_recovery_email_adress",
            //            "villa_email_address",
        ];
        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";
    }

    async function saveVilla(event: Event) {
        event.preventDefault();

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

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

        if (isEditing && currentEditingId) {
            const { error } = await supabase
                .from("vb_villas")
                .update(newVilla)
                .eq("id", currentEditingId);
            if (error) {
                alert("Error updating villa: " + error.message);
                return;
            }
        } else {
            const { error } = await supabase
                .from("vb_villas")
                .insert([newVilla]);
            if (error) {
                alert("Error adding villa: " + error.message);
                return;
            }
        }

        await fetchVillas();
        showModal = false;
    }

    async function deleteVilla(id: string) {
        if (confirm("Are you sure you want to delete this villa?")) {
            const { error } = await supabase
                .from("vb_villas")
                .delete()
                .eq("id", id);
            if (error) {
                alert("Error deleting villa: " + error.message);
            } else {
                await fetchVillas();
            }
        }
    }

    // Reset form errors when modal is closed
    $: if (!showModal) {
        formErrors.set({});
    }

    //  update villa status
    async function updateVillaStatus(villaId: string, status: string) {
        const { error } = await supabase
            .from("vb_villas")
            .update({ villa_status: status })
            .eq("id", villaId);
        if (error) {
            console.error("Error updating villa status:", error);
        } else {
            await fetchVillas();
        }
    }

    //  update villa condition
    async function updateVillaCondition(villaId: string, condition: string) {
        const { error } = await supabase
            .from("vb_villas")
            .update({ villa_condition: condition })
            .eq("id", villaId);
        if (error) {
            console.error("Error updating villa condition:", error);
        } else {
            await fetchVillas();
        }
    }
</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">🏡 Villa List</h2>
            <p class="text-sm text-gray-500">
                Manage and track villas efficiently
            </p>
        </div>
        <div class="flex flex-col sm:flex-row sm:items-center gap-2">
            <input
                type="text"
                placeholder="🔍 Search by name..."
                class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-4 py-2 rounded-xl text-sm w-64 transition"
                on:input={(e) => {
                    const searchTerm = (
                        e.target as HTMLInputElement
                    ).value.toLowerCase();
                    fetchVillas(searchTerm, "created_at", "desc", limit, 0);
                }}
            />
            <!-- filter -->
            <select
                class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-4 py-2 rounded-xl text-sm w-48 transition"
                on:change={(e) => {
                    const sortBy = (e.target as HTMLSelectElement).value;
                    fetchVillas(null, sortBy, "desc", limit, 0);
                }}
            >
                <option value="created_at">Sort by Created At</option>
                <option value="villa_name">Sort by Villa Name</option>
                <option value="villa_manager">Sort by Villa Manager</option>
                <option value="villa_location">Sort by Villa Location</option>
                <option value="villa_status">Sort by Villa Status</option>
                <option value="no_of_bedrooms">Sort by No Of Bedrooms</option>
                <option value="villa_condition">Sort by Villa Condition</option>
                <option value="season_1_rate">Sort by Season 1 Rate</option>
                <option value="season_2_rate">Sort by Season 2 Rate</option>
                <option value="season_3_rate">Sort by Season 3 Rate</option>
                <option value="season_4_rate">Sort by Season 4 Rate</option>
                <option value="season_5_rate">Sort by Season 5 Rate</option>
                <option value="season_6_rate">Sort by Season 6 Rate</option>
                <option value="season_7_rate">Sort by Season 7 Rate</option>
            </select>
            <button
                class="bg-gray-200 text-gray-700 px-4 py-2 rounded-xl hover:bg-gray-300 text-sm transition"
                on:click={() =>
                    fetchVillas(null, "created_at", "desc", limit, 0)}
            >
                🔄 Reset
            </button>
            <button
                class="bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-700 text-sm transition"
                on:click={() => openModal()}
            >
                ➕ Add Villa
            </button>
        </div>
    </div>

    <div class="overflow-x-auto rounded-lg shadow mb-4">
        <table class="min-w-[1000px] divide-y divide-gray-200 text-sm w-max">
            <thead class="bg-gray-100">
                <tr>
                    {#each columns as col}
                        {#if col.key === "villa_name"}
                            <th
                                class="sticky left-0 px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
                                style="background-color: #f0f8ff; z-index: 10;"
                            >
                                {col.title}
                            </th>
                        {:else}
                            <th
                                class="px-4 py-3 text-left font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap"
                            >
                                {col.title}
                            </th>
                        {/if}
                    {/each}
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 bg-white">
                {#each allRows as row}
                    <tr class="hover:bg-gray-50 transition">
                        {#each columns as col}
                            {#if col.key === "villa_name"}
                                <td
                                    class="sticky left-0 px-4 py-2 font-medium text-blue-600"
                                    style="background-color: #f0f8ff; cursor: pointer;"
                                >
                                    {row[col.key]}
                                </td>
                            {:else if col.key === "created_at"}
                                <td class="px-4 py-2 text-gray-500">
                                    {new Date(row[col.key]).toLocaleDateString(
                                        "en-US",
                                        {
                                            year: "numeric",
                                            month: "short",
                                            day: "numeric",
                                        },
                                    )}
                                </td>
                            {:else if col.key === "villa_status"}
                                <!-- dropdown -->
                                <td class="px-4 py-2">
                                    <select
                                        class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-3 py-1 rounded text-sm w-full"
                                        bind:value={row[col.key]}
                                        on:change={(e) => {
                                            (row as any)[col.key] = (
                                                e.target as HTMLSelectElement
                                            ).value;
                                            updateVillaStatus(
                                                row.id,
                                                (row as any)[col.key],
                                            );
                                        }}
                                    >
                                        <option value="" disabled
                                            >SELECT STATUS</option
                                        >
                                        <option value="Active">ACTIVE</option>
                                        <option value="Inactive"
                                            >INACTIVE</option
                                        >
                                    </select>
                                </td>
                            {:else if col.key === "villa_condition"}
                                <td class="px-4 py-2">
                                    <select
                                        class="border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:outline-none px-3 py-1 rounded text-sm w-full"
                                        bind:value={row[col.key]}
                                        on:change={(e) => {
                                            (row as any)[col.key] = (
                                                e.target as HTMLSelectElement
                                            ).value;
                                            updateVillaCondition(
                                                row.id,
                                                (row as any)[col.key],
                                            );
                                        }}
                                    >
                                        <option value="" disabled
                                            >SELECT CONDITION</option
                                        >
                                        <option value="Occupied"
                                            >Occupied</option
                                        >
                                        <option value="Vacant clean"
                                            >Vacant clean</option
                                        >
                                        <option value="Vacant dirty"
                                            >Vacant Dirty</option
                                        >
                                        <option value="Ready for Inspection"
                                            >Ready for Inspection</option
                                        >
                                    </select>
                                </td>
                            {:else if col.key === "villa_manager"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "villa_location"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "no_of_bedrooms"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "created_by"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "villa_email_address"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "owner_portal_username"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "owner_portal_password"}
                                <td class="px-4 py-2 text-gray-500">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "closeable_living_room"}
                                <td class="px-4 py-2">
                                    {row[col.key] ? "✔️ Yes" : "❌ No"}
                                </td>
                            {:else if col.key === "monthly_rental_pre_approved_status"}
                                <td class="px-4 py-2">
                                    {row[col.key] ? "✔️ Yes" : "❌ No"}
                                </td>
                            {:else if col.key === "long_term_rental_pre_approval"}
                                <td class="px-4 py-2">
                                    {row[col.key] ? "✔️ Yes" : "❌ No"}
                                </td>
                            {:else if col.key === "pet_allowed_pre_approval_status"}
                                <td class="px-4 py-2">
                                    {row[col.key] ? "✔️ Yes" : "❌ No"}
                                </td>
                            {:else if col.key === "season_1_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_2_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_3_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_4_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_5_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_6_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "season_7_rate"}
                                <td class="px-4 py-2">
                                    {row[col.key] || "N/A"}
                                </td>
                            {:else if col.key === "actions"}
                                <td class="px-4 py-2">
                                    <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={() => deleteVilla(row.id)}
                                    >
                                        🗑️ Delete
                                    </button>
                                </td>
                            {:else}
                                <td class="px-4 py-2 text-gray-700"
                                    >{row[col.key as keyof Villa]}</td
                                >
                            {/if}
                        {/each}
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>
    <!-- Pagination controls -->
    <div class="flex justify-between items-center text-sm">
        <div>
            Showing {currentPage} of {totalPages} pages ({allRows.length} items total)
        </div>
        <div class="space-x-2">
            <button
                class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
                on:click={() => goToPage(currentPage - 1)}
                disabled={currentPage === 1}
            >
                Previous
            </button>
            {#each Array(totalPages)
                .fill(0)
                .map((_, i) => i + 1) as page}
                <button
                    class="px-3 py-1 rounded border text-sm {currentPage ===
                    page
                        ? 'bg-blue-600 text-white border-blue-600'
                        : 'bg-white border-gray-300 hover:bg-gray-100'}"
                    on:click={() => goToPage(page)}
                >
                    {page}
                </button>
            {/each}
            <button
                class="px-3 py-1 rounded border border-gray-300 bg-white hover:bg-gray-100 disabled:opacity-50"
                on:click={() => goToPage(currentPage + 1)}
                disabled={currentPage === totalPages}
            >
                Next
            </button>
        </div>
    </div>
</div>

<!-- Modal -->
{#if showModal}
    <div
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
        <form
            class="bg-white p-6 rounded shadow-lg w-[600px] max-h-[90vh] overflow-y-auto space-y-4"
            on:submit={saveVilla}
        >
            <h3 class="text-lg font-semibold">
                {isEditing ? "Edit Villa" : "Add New Villa"}
            </h3>
            {#each formColumns as col}
                {#if col.key === "villa_status"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}
                            <select
                                name={col.key}
                                class="w-full border px-3 py-2 rounded {errorClass(
                                    col.key,
                                )}"
                                bind:value={newVilla[col.key]}
                            >
                                <option value="" disabled selected
                                    >SELECT STATUS</option
                                >
                                <option value="available">ACTIVE</option>
                                <option value="rented">INACTIVE</option>
                            </select>
                        </label>
                    </div>
                    {#if $formErrors.villa_status}
                        <p class="text-red-500 text-xs">
                            {$formErrors.villa_status}
                        </p>
                    {/if}
                {:else if col.key === "villa_condition"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <select
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            bind:value={newVilla[col.key]}
                        >
                            <option value="" disabled selected
                                >SELECT CONDITION</option
                            >
                            <option value="new">New</option>
                            <option value="good">Good</option>
                            <option value="needs_maintenance"
                                >Needs Maintenance</option
                            >
                        </select>
                    </div>
                    {#if $formErrors.villa_condition}
                        <p class="text-red-500 text-xs">
                            {$formErrors.villa_condition}
                        </p>
                    {/if}
                {:else if col.key === "closeable_living_room"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <select
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            bind:value={newVilla[col.key]}
                        >
                            <option value="" disabled selected
                                >SELECT OPTION</option
                            >
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>
                    {#if $formErrors.closeable_living_room}
                        <p class="text-red-500 text-xs">
                            {$formErrors.closeable_living_room}
                        </p>
                    {/if}
                {:else if col.key === "monthly_rental_pre_approved_status"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <select
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            bind:value={newVilla[col.key]}
                        >
                            <option value="" disabled selected
                                >SELECT OPTION</option
                            >
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>
                    {#if $formErrors.monthly_rental_pre_approved_status}
                        <p class="text-red-500 text-xs">
                            {$formErrors.monthly_rental_pre_approved_status}
                        </p>
                    {/if}
                {:else if col.key === "long_term_rental_pre_approval"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <select
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            bind:value={newVilla[col.key]}
                        >
                            <option value="" disabled selected
                                >SELECT OPTION</option
                            >
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>
                    {#if $formErrors.long_term_rental_pre_approval}
                        <p class="text-red-500 text-xs">
                            {$formErrors.long_term_rental_pre_approval}
                        </p>
                    {/if}
                {:else if col.key === "pet_allowed_pre_approval_status"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <select
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            bind:value={newVilla[col.key]}
                        >
                            <option value="" disabled selected
                                >SELECT OPTION</option
                            >
                            <option value="true">Yes</option>
                            <option value="false">No</option>
                        </select>
                    </div>
                    {#if $formErrors.pet_allowed_pre_approval_status}
                        <p class="text-red-500 text-xs">
                            {$formErrors.pet_allowed_pre_approval_status}
                        </p>
                    {/if}
                {:else if col.key === "session_1_rate" || col.key === "session_2_rate" || col.key === "session_3_rate" || col.key === "session_4_rate" || col.key === "session_5_rate" || col.key === "session_6_rate" || col.key === "session_7_rate"}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <input
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            type="number"
                            bind:value={newVilla[col.key]}
                            placeholder={col.title}
                        />
                    </div>
                    {#if $formErrors[col.key]}
                        <p class="text-red-500 text-xs">
                            {$formErrors[col.key]}
                        </p>
                    {/if}
                {:else}
                    <div class="space-y-1">
                        <label class="block text-sm font-medium text-gray-700"
                            >{col.title}</label
                        >
                        <input
                            name={col.key}
                            class="w-full border px-3 py-2 rounded {errorClass(
                                col.key,
                            )}"
                            type="text"
                            bind:value={newVilla[col.key]}
                            placeholder={col.title}
                        />
                    </div>
                    {#if $formErrors[col.key]}
                        <p class="text-red-500 text-xs">
                            {$formErrors[col.key]}
                        </p>
                    {/if}
                {/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)}
                >
                    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}
