<script>
    import { useDictionaryForm } from "$lib/components/composable/use-dictionary-form.svelte";
    import FormPageContainer from "$lib/components/reusable/form/form-page-container.svelte";
    import DictionaryFormRenderer from "$lib/components/reusable/form/dictionary-form-renderer.svelte";
    import { toast } from "svelte-sonner";
    import ReusableAlertDialog from "$lib/components/reusable/reusable-alert-dialog.svelte";
    import * as Tabs from "$lib/components/ui/tabs/index.js";
    import { useForm } from "$lib/components/composable/use-form.svelte";
    import { buildTestPayload, testCalSchema, testCalInitialForm, testCalDefaultErrors, testCalFormFields, refNumInitialForm, refNumFormFields } from "$lib/components/dictionary/test/config/test-form-config";
    import ReusableEmpty from "$lib/components/reusable/reusable-empty.svelte";
    import RefNum from "./tabs/ref-num.svelte";
    import RefTxt from "./tabs/ref-txt.svelte";
    import Calculation from "./tabs/calculation.svelte";

    let props = $props();

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

    const { formState } = masterDetail;

    const calFormState = useForm({
        schema: null,
        initialForm: testCalInitialForm,
    });

    const refNumState = useForm({
        schema: null,
        initialForm: refNumInitialForm,
        defaultErrors: {},
        mode: 'create',
        modeOpt: 'default',
        saveEndpoint: null,
        editEndpoint: null,
    })

    const helpers = useDictionaryForm(formState);

    const handlers = {
        clearForm: () => {
            formState.reset();
        }
    };

    const actions = formActions(handlers);

    let showConfirm = $state(false);

    async function handleSave() {
        const mainForm = masterDetail.formState.form;
        const calForm = calFormState.form;
        const refForm = refNumState.form;

        const payload = buildTestPayload({
            mainForm,
            calForm,
            refForm,
            testType: mainForm.TestType
        });
        console.log(payload);
        // const result = await formState.save(masterDetail.mode);

        // toast('Test Created!');
        // masterDetail?.exitForm(true);
    }

    const primaryAction = $derived({
        label: 'Save',
        onClick: handleSave,
        disabled: helpers.hasErrors || formState.isSaving.current,
        loading: formState.isSaving.current
    });

    const secondaryActions = [];

    // ==================================================================
    
    let availableTabs = $derived.by(() => {
        const testType = formState?.form?.TestType;
        
        switch(testType) {
            case 'TEST':
            case 'PARAM':
                return ['definition', 'map', 'reference'];
            case 'CALC':
                return ['definition', 'calculation', 'map', 'reference'];
            case 'GROUP':
                return ['definition', 'group'];
            default:
                return ['definition'];
        }
    });

    let disabledResultTypes = $derived.by(() => {
        const testType = formState?.form?.TestType;
        
        switch(testType) {
            case 'TEST':
            case 'PARAM':
                return [];
            case 'CALC':
                return ['RANGE', 'TEXT', 'VSET', 'NORES'];
            case 'GROUP':
                return ['NMRIC', 'RANGE', 'TEXT', 'VSET', 'NORES'];
            case 'TITLE':
                return ['NMRIC', 'RANGE', 'TEXT', 'VSET', 'NORES'];
            default:
                return [];
        }
    });

    let disabledReferenceTypes = $derived.by(() => {
        const resultType = formState?.form?.ResultType;
        
        switch(resultType) {
            case 'NMRIC':
                return ['TEXT', 'VSET', 'NOREF'];
            case 'RANGE':
                return ['TEXT', 'VSET', 'NOREF'];
            case 'TEXT':
                return ['RANGE', 'THOLD', 'VSET', 'NOREF'];
            case 'VSET':
                return ['RANGE', 'THOLD', 'TEXT', 'NOREF'];
            case 'NORES':
                return ['RANGE', 'THOLD', 'TEXT', 'VSET'];
            default:
                return ['RANGE', 'THOLD', 'TEXT', 'VSET', 'NOREF'];
        }
    });

    let refComponent = $derived.by(() => {
        const refType = formState.form.RefType;
        if (refType === 'RANGE' || refType === 'THOLD') return 'numeric';
        if (refType === 'TEXT' || refType === 'VSET') return 'text';
        return null;
    });

    let activeTab = $state('definition');

    $effect(() => {
        if (!availableTabs.includes(activeTab)) {
            activeTab = availableTabs[0];
        }
    });

</script>

<FormPageContainer title="Create Test" {primaryAction} {secondaryActions} {actions}>
    <Tabs.Root bind:value={activeTab} class="w-full h-full">
        <Tabs.List>
            {#if availableTabs.includes('definition')}
                <Tabs.Trigger value="definition">Definition</Tabs.Trigger>
            {/if}
            {#if availableTabs.includes('calculation')}
                <Tabs.Trigger value="calculation">Calculation</Tabs.Trigger>
            {/if}
            {#if availableTabs.includes('group')}
                <Tabs.Trigger value="group">Group</Tabs.Trigger>
            {/if}
            {#if availableTabs.includes('reference')}
                <Tabs.Trigger value="reference">Reference</Tabs.Trigger>
            {/if}
            {#if availableTabs.includes('map')}
                <Tabs.Trigger value="map">Map</Tabs.Trigger>
            {/if}
        </Tabs.List>
        <Tabs.Content value="definition">
            <DictionaryFormRenderer 
                {formState}
                formFields={formFields}
                mode="create"
                {disabledResultTypes}
                {disabledReferenceTypes}
            />
        </Tabs.Content>
        <Tabs.Content value="calculation">
            <Calculation {calFormState}/>
        </Tabs.Content>
        <Tabs.Content value="group">
            group
        </Tabs.Content>
        <Tabs.Content value="map">
            map
        </Tabs.Content>
        <Tabs.Content value="reference">
            <div class="w-full h-full flex items-start">
                {#if refComponent === 'numeric'}
                    <RefNum {refNumState} {refNumFormFields} refType={formState.form.RefType}/>
                {:else if refComponent === 'text'}
                    <RefTxt {formState} />
                {:else}
                    <div class="h-full w-full flex items-center">
                        <ReusableEmpty desc="Select a Reference Type" />
                    </div>
                {/if}
            </div>
        </Tabs.Content>
    </Tabs.Root>
    
</FormPageContainer>

<ReusableAlertDialog
    bind:open={masterDetail.showExitConfirm}
    onConfirm={masterDetail.confirmExit}
/>