<script>
    import { formatUTCDate } from "$lib/utils/formatUTCDate";
    import { detailSections, viewActions } from "$lib/components/order/ordertest/config/ordertest-config";
    import TopbarWrapper from "$lib/components/topbar/topbar-wrapper.svelte";
    import ReusableEmpty from "$lib/components/reusable/reusable-empty.svelte";
    import * as Table from "$lib/components/ui/table/index.js";
    import { Spinner } from "$lib/components/ui/spinner/index.js";
    import ClipboardXIcon from "@lucide/svelte/icons/clipboard-x";

    let props = $props();

    const { masterDetail, formFields, formActions, schema } = props.context;

    let order = $derived(masterDetail?.selectedItem?.data);

    const handlers = {
        editOrder: () => masterDetail.enterEdit("data"),
    };

    const actions = viewActions(handlers);

    function getFieldValue(field) {
        if (!order) return "-";

        if (field.keys) {
            return field.keys
                .map(k => field.parentKey ? order[field.parentKey]?.[k] : order[k])
                .filter(val => val && val.trim() !== "")
                .join(" / ");
        }

        return field.parentKey ? order[field.parentKey]?.[field.key] : order[field.key];
    }

</script>

{#snippet DetailsTable({ value, label })}
    <div class="space-y-1.5 w-full">
        <dt class="text-xs font-medium text-muted-foreground uppercase tracking-wider">
            {label}
        </dt>
        <dd>
            {#if value && Array.isArray(value) && value.length > 0}
                <div class="border rounded-md">
                    <Table.Root>
                         <Table.Header>
                            <Table.Row>
                                <Table.Head>Test Code</Table.Head>
                                <Table.Head>Test Name</Table.Head>
                                <!-- <Table.Head>Discipline</Table.Head> -->
                                <!-- <Table.Head>Create Date</Table.Head> -->
                            </Table.Row>
                         </Table.Header>
                         <Table.Body>
                            {#each value as row, i}
                                <Table.Row>
                                    <Table.Cell>{row.TestSiteCode ?? '-'}</Table.Cell>
                                    <Table.Cell>{row.TestSiteName ?? '-'}</Table.Cell>
                                    <!-- <Table.Cell>{row.Discipline.DisciplineName ?? '-'}</Table.Cell> -->
                                    <!-- <Table.Cell>{row.CreateDate}</Table.Cell> -->
                                </Table.Row>
                            {/each}
                         </Table.Body>
                    </Table.Root>
                </div>
            {:else}
                <span class="text-sm font-medium">-</span>
            {/if}
        </dd>
    </div>
{/snippet}

{#snippet Fieldset({ value, label, isUTCDate = false })}
    <div class="space-y-1.5">
        <dt class="text-xs font-medium text-muted-foreground uppercase tracking-wider">
            {label}
        </dt>
        <dd class="text-sm font-medium">
            {#if isUTCDate}
                {formatUTCDate(value)}
            {:else}
                {value ?? "-"}
            {/if}
        </dd>
    </div>
{/snippet}

{#if masterDetail.isLoadingDetail}
    <div class="h-full w-full flex items-center justify-center">
        <Spinner class="size-6" />
    </div> 
{:else if masterDetail.selectedItem}
    <div class="flex flex-col px-2 py-1 gap-2 h-full w-full">
        <TopbarWrapper 
            title={masterDetail.selectedItem.data.OrderID} 
            {actions} 
        />
        <div class="flex-1 min-h-0 overflow-y-auto space-y-4">
            {#each detailSections as section}
                <div class="flex flex-col px-4 py-2 gap-2">
                    <div class="{section.class} w-full">
                        {#each section.fields as field}
                            {#if field.fullWidth}
                                <div class="col-span-2 mt-2">
                                    {#if field.key === "Tests"}
                                        {@render DetailsTable({ label: field.label, value: getFieldValue(field) })}
                                    {:else}
                                        {@render Fieldset({ label: field.label, value: getFieldValue(field), isUTCDate: field.isUTCDate })}
                                    {/if}
                                </div>
                            {:else if field.key === "Tests"}
                                {@render DetailsTable({
                                    label: field.label,
                                    value: getFieldValue(field),
                                })}
                            {:else}
                                {@render Fieldset({
                                    label: field.label,
                                    value: getFieldValue(field),
                                    isUTCDate: field.isUTCDate
                                })}
                            {/if}
                        {/each}
                    </div>
                </div>
            {/each}
        </div>
    </div>
{:else}
    <ReusableEmpty icon={ClipboardXIcon} desc="Select an order to see details"/>
{/if}