<script lang="ts">
    import { createEventDispatcher } from "svelte";

    type ConditionType =
        | "NEW"
        | "GOOD"
        | "AVERAGE"
        | "POOR"
        | "SUBSTANDARD"
        | "BROKEN";

    type InventoryInsert = {
        item_name: string;
        villa_id: string;
        item_location: string;
        brand_color_material: string;
        condition: ConditionType;
        remarks: string;
        created_at: string;
        updated_at: string;
    };

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

    export let showModal: boolean;
    export let isEditing: boolean;
    export let formData: InventoryInsert;
    export let villaItems: Villa[];
    export let isLoading: boolean = false;

    const dispatch = createEventDispatcher();

    let formErrors: Record<string, string> = {};

    function validateForm(): boolean {
        formErrors = {};
        let isValid = true;

        if (!formData.item_name) {
            formErrors.item_name = "Item name is required.";
            isValid = false;
        }
        if (!formData.villa_id) {
            formErrors.villa_id = "Villa name is required.";
            isValid = false;
        }
        if (!formData.item_location) {
            formErrors.item_location = "Item location is required.";
            isValid = false;
        }
        if (!formData.brand_color_material) {
            formErrors.brand_color_material =
                "Brand/Color/Material is required.";
            isValid = false;
        }
        if (!formData.condition) {
            formErrors.condition = "Condition is required.";
            isValid = false;
        }
        if (formData.remarks && formData.remarks.length > 500) {
            formErrors.remarks = "Remarks cannot exceed 500 characters.";
            isValid = false;
        }
        return isValid;
    }

    function handleSubmit() {
        if (validateForm()) {
            dispatch("submit", formData);
        }
    }

    function closeModal() {
        formErrors = {}; // Clear errors when closing
        dispatch("close");
    }
</script>

{#if showModal}
    <div
        class="fixed inset-0 bg-black bg-opacity-50 z-50 overflow-y-auto flex items-center justify-center p-4"
        on:click|self={closeModal}
    >
        <form
            on:submit|preventDefault={handleSubmit}
            class="w-full max-w-lg bg-white p-8 rounded-2xl shadow-2xl space-y-5 transform transition-all duration-300 ease-out scale-100 opacity-100"
        >
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-2xl font-bold text-gray-800">
                    {isEditing ? "Edit Item" : "Add New Item"}
                </h2>
                <button
                    type="button"
                    class="text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-100 transition"
                    on:click={closeModal}
                >
                    <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-6 w-6"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                    >
                        <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M6 18L18 6M6 6l12 12"
                        />
                    </svg>
                </button>
            </div>

            <div>
                <label
                    for="item_name"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Item Name</label
                >
                <input
                    type="text"
                    id="item_name"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.item_name
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.item_name}
                    placeholder="e.g., Living Room Sofa"
                    required
                />
                {#if formErrors.item_name}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.item_name}
                    </p>
                {/if}
            </div>

            <div>
                <label
                    for="villa_id"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Villa Name</label
                >
                <select
                    id="villa_id"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.villa_id
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.villa_id}
                    required
                >
                    <option value="" disabled>Select Villa</option>
                    {#each villaItems as villa}
                        <option value={villa.id}>
                            {villa.villa_name}
                        </option>
                    {/each}
                </select>
                {#if formErrors.villa_id}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.villa_id}
                    </p>
                {/if}
            </div>

            <div>
                <label
                    for="item_location"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Item Location</label
                >
                <input
                    type="text"
                    id="item_location"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.item_location
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.item_location}
                    placeholder="e.g., Master Bedroom, Kitchen"
                    required
                />
                {#if formErrors.item_location}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.item_location}
                    </p>
                {/if}
            </div>

            <div>
                <label
                    for="brand_color_material"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Brand/Color/Material</label
                >
                <input
                    type="text"
                    id="brand_color_material"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.brand_color_material
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.brand_color_material}
                    placeholder="e.g., IKEA / White / Wood"
                    required
                />
                {#if formErrors.brand_color_material}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.brand_color_material}
                    </p>
                {/if}
            </div>

            <div>
                <label
                    for="condition"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Condition</label
                >
                <select
                    id="condition"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.condition
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.condition}
                    required
                >
                    <option value="NEW">New</option>
                    <option value="GOOD">Good</option>
                    <option value="AVERAGE">Average</option>
                    <option value="POOR">Poor</option>
                    <option value="SUBSTANDARD">Substandard</option>
                    <option value="BROKEN">Broken</option>
                </select>
                {#if formErrors.condition}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.condition}
                    </p>
                {/if}
            </div>

            <div>
                <label
                    for="remarks"
                    class="block text-sm font-medium text-gray-700 mb-1"
                    >Remarks</label
                >
                <textarea
                    id="remarks"
                    class="w-full border border-gray-300 p-3 rounded-lg focus:ring-blue-500 focus:border-blue-500 transition {formErrors.remarks
                        ? 'border-red-500'
                        : ''}"
                    bind:value={formData.remarks}
                    placeholder="Optional remarks about the item"
                    rows="3"
                ></textarea>
                {#if formErrors.remarks}
                    <p class="text-red-500 text-xs mt-1">
                        {formErrors.remarks}
                    </p>
                {/if}
            </div>

            <button
                type="submit"
                class="w-full bg-blue-600 text-white font-semibold px-4 py-3 rounded-lg hover:bg-blue-700 transition duration-200 shadow-md flex items-center justify-center gap-2"
                disabled={isLoading}
            >
                {#if isLoading}
                    <svg
                        class="animate-spin h-5 w-5 text-white"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                    >
                        <circle
                            class="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            stroke-width="4"
                        ></circle>
                        <path
                            class="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        ></path>
                    </svg>
                    Saving...
                {:else}
                    {isEditing ? "Update Item" : "Add Item"}
                {/if}
            </button>
        </form>
    </div>
{/if}

<style>
    /* Modal entry animation */
    .transform {
        transition: all 0.3s ease-out;
    }
    .scale-100 {
        transform: scale(1);
    }
    .opacity-100 {
        opacity: 1;
    }
    /* Initial state for hidden modal - you'd set this with a conditional class or just let Tailwind apply it on removal */
</style>
