<script>
    import DictionaryFormRenderer from "$lib/components/reusable/form/dictionary-form-renderer.svelte";
    import { Separator } from "$lib/components/ui/separator/index.js";
    import { Button } from "$lib/components/ui/button/index.js";
    import * as Table from "$lib/components/ui/table/index.js";
    import PencilIcon from "@lucide/svelte/icons/pencil";
    import Trash2Icon from "@lucide/svelte/icons/trash-2";
    import { untrack } from "svelte";

    let { tempMap = $bindable([]), resetMap = $bindable(), ...props } = $props()

    let editingId = $state(null);
    let idCounter = $state(0);

    resetMap = () => {
        tempMap = [];
    };

    function snapshotForm() {
        return untrack(() => {
            const f = props.mapFormState.form;
            const options = {};
            for (const key in props.mapFormState.selectOptions) {
                options[key] = [...props.mapFormState.selectOptions[key]];
            }
            return {
                HostType: f.HostType ?? "",
                HostID: f.HostID ?? "",
                HostTestCode: f.HostTestCode ?? "",
                HostTestName: f.HostTestName ?? "",
                ClientType: f.ClientType ?? "",
                ClientID: f.ClientID ?? "",
                ClientTestCode: f.ClientTestCode ?? "",
                ClientTestName: f.ClientTestName ?? "",
                ConDefID: f.ConDefID ?? "",
                options: options
            };
        });
    }

    function resetForm() {
        props.mapFormState.reset?.();
        editingId = null;
    }

    function handleInsert() {
        const row = {
            id: ++idCounter,
            ...snapshotForm()
        };

        tempMap = [...tempMap, row];

        resetForm();
    }

    async function handleEdit(row) {
        editingId = row.id;

        untrack(() => {
            const f = props.mapFormState.form;
            console.log(row);
            f.HostType       = row.HostType;
            f.HostID         = row.HostID;
            f.HostTestCode   = row.HostTestCode;
            f.HostTestName   = row.HostTestName;
            f.ClientType     = row.ClientType;
            f.ClientID       = row.ClientID;
            f.ClientTestCode = row.ClientTestCode;
            f.ClientTestName = row.ClientTestName;
            f.ConDefID       = row.ConDefID;

            if (row.options) {
                for (const key in row.options) {
                    props.mapFormState.selectOptions[key] = row.options[key];
                }
            }
        });
    }

    function handleUpdate() {
        tempMap = tempMap.map((row) =>
            row.id === editingId ? { id: row.id, ...snapshotForm() } : row
        );
        resetForm();
    }

    function handleCancelEdit() {
        resetForm();
    }

    function handleRemove(id) {
        tempMap = tempMap.filter((row) => row.id !== id);
        if (editingId === id) resetForm();
    }

    function getLabel(fieldKey, value, rowId) {
        const row = tempMap.find(r => r.id === rowId);
        if (row && row.options) {
            const opts = row.options[fieldKey] ?? [];
            const found = opts.find((o) => o.value == value);
            return found ? found.label : value;
        }
        return value;
    }
</script>

<div class="flex flex-col gap-4 w-full">
    <div>
        <DictionaryFormRenderer 
            formState={props.mapFormState}
            formFields={props.testMapFormFields}
        />
        <div class="flex gap-2 mt-1 ms-2">
            {#if editingId !== null}
                <Button size="sm" class="cursor-pointer" onclick={handleUpdate}>
                    Update
                </Button>
                <Button size="sm" variant="outline" class="cursor-pointer" onclick={handleCancelEdit}>
                    Cancel
                </Button>
            {:else}
                <Button size="sm" class="cursor-pointer" onclick={handleInsert}>
                    Insert
                </Button>
            {/if}
        </div>
    </div>

    <Separator />

    <div>
        <Table.Root>
            <Table.Header>
                <Table.Row class="hover:bg-transparent">
                    <Table.Head>Host Type</Table.Head>
                    <Table.Head>Host ID</Table.Head>
                    <Table.Head>Host Test Code</Table.Head>
                    <Table.Head>Host Test Name</Table.Head>
                    <Table.Head>Client Type</Table.Head>
                    <Table.Head>Client ID</Table.Head>
                    <Table.Head>Client Test Code</Table.Head>
                    <Table.Head>Client Test Name</Table.Head>
                    <Table.Head>Container</Table.Head>
                    <Table.Head class="w-[80px]"></Table.Head>
                </Table.Row>
            </Table.Header>
            <Table.Body>
                {#if tempMap.length === 0}
                    <Table.Row>
                        <Table.Cell colspan={9} class="text-center text-muted-foreground py-6">
                            No data. Fill the form above and click Insert.
                        </Table.Cell>
                    </Table.Row>
                {:else}
                    {#each tempMap as row (row.id)}
                        <Table.Row 
                            class="cursor-pointer hover:bg-muted/50"
                        >
                            <Table.Cell>{row.HostType}</Table.Cell>
                            <Table.Cell>{row.HostID}</Table.Cell>
                            <Table.Cell>{row.HostTestCode}</Table.Cell>
                            <Table.Cell>{row.HostTestName}</Table.Cell>
                            <Table.Cell>{row.ClientType}</Table.Cell>
                            <Table.Cell>{row.ClientID ? getLabel("ClientID", row.ClientID, row.id) : "-"}</Table.Cell>
                            <Table.Cell>{row.ClientTestCode ? getLabel("ClientTestCode", row.ClientTestCode, row.id) : "-"}</Table.Cell>
                            <Table.Cell>{row.ClientTestName ? getLabel("ClientTestName", row.ClientTestName, row.id) : "-"}</Table.Cell>
                            <Table.Cell>{row.ConDefID ? getLabel("ConDefID", row.ConDefID, row.id) : "-"}</Table.Cell>
                            <Table.Cell>
                                <div class="flex gap-1">
                                    <Button
                                        size="icon"
                                        variant="ghost"
                                        class="h-7 w-7 cursor-pointer"
                                        onclick={() => handleEdit(row)}
                                    >
                                        <PencilIcon class="h-3.5 w-3.5" />
                                    </Button>
                                    <Button
                                        size="icon"
                                        variant="ghost"
                                        class="h-7 w-7 cursor-pointer"
                                        onclick={() => handleRemove(row.id)}
                                    >
                                        <Trash2Icon class="h-3.5 w-3.5" />
                                    </Button>
                                </div>
                            </Table.Cell>
                        </Table.Row>
                    {/each}
                {/if}
            </Table.Body>
        </Table.Root>
    </div>
</div>