<script lang="ts">
    import { Button } from "$lib/components/ui/button";
    import * as Dialog from "$lib/components/ui/dialog";
    import { Input } from "$lib/components/ui/input";
    import { Label } from "$lib/components/ui/label";
    import * as Tabs from "$lib/components/ui/tabs";
    import { Switch } from "$lib/components/ui/switch"; 
    import { createCompany, updateCompany, type Company } from "$lib/api/dashboard/a76/general_catalogs/company";
    import { companyStore } from "$lib/stores/company.svelte";

    let {
        open = $bindable(false),
        item = null,
        onSuccess
    }: {
        open: boolean;
        item?: Company | null;
        onSuccess?: () => void;
    } = $props();

    const isEdit = $derived(!!item);
    const title = $derived(isEdit ? "Editar Empresa" : "Nueva Empresa");

    // Inicialización completa con todos los campos del modelo
    let formData = $state({
        // General
        name: '',
        rfc: '',
        curp: '',
        main_activity: '',
        
        // Programas
        program: '',
        program_number: '',
        prosec: 0,
        prosec_authorization: '',
        
        // Responsable
        responsible_name: '',
        responsible_last_name: '',
        responsible_mother_last_name: '',
        responsible_rfc: '',
        position: '',
        
        // Configuración / Operativo
        manufacturer_id: '',
        is_service_company: false,
        order_format_type: '',
        
        // Certificaciones
        ctpat_svi: '',
        trusted_exporter_number: ''
    });

    let loading = $state(false);
    let error = $state<string | null>(null);

    // Cargar datos al abrir para editar
    $effect(() => {
        if (item) {
            formData = {
                name: item.name || '',
                rfc: item.rfc || '',
                curp: item.curp || '',
                main_activity: item.main_activity || '',
                
                program: item.program || '',
                program_number: item.program_number || '',
                prosec: item.prosec || 0,
                prosec_authorization: item.prosec_authorization || '',
                
                responsible_name: item.responsible_name || '',
                responsible_last_name: item.responsible_last_name || '',
                responsible_mother_last_name: item.responsible_mother_last_name || '',
                responsible_rfc: item.responsible_rfc || '',
                position: item.position || '',
                
                manufacturer_id: item.manufacturer_id || '',
                is_service_company: item.is_service_company || false,
                order_format_type: item.order_format_type || '',
                
                ctpat_svi: item.ctpat_svi || '',
                trusted_exporter_number: item.trusted_exporter_number || ''
            };
        } else {
            // Reset manual si es nuevo 
            formData = {
                name: '', rfc: '', curp: '', main_activity: '',
                program: '', program_number: '', prosec: 0, prosec_authorization: '',
                responsible_name: '', responsible_last_name: '', responsible_mother_last_name: '', responsible_rfc: '', position: '',
                manufacturer_id: '', is_service_company: false, order_format_type: '',
                ctpat_svi: '', trusted_exporter_number: ''
            };
        }
    });

    async function handleSubmit() {
        error = null;
        loading = true;

        try {
            if (!formData.name.trim()) throw new Error('El nombre es requerido');
            if (!formData.rfc.trim()) throw new Error('El RFC es requerido');

            // Construir payload limpiando strings vacíos a null
            const dataToSend = {
                name: formData.name.trim(),
                rfc: formData.rfc.trim(),
                curp: formData.curp.trim() || null,
                main_activity: formData.main_activity.trim() || null,
                
                program: formData.program.trim() || null,
                program_number: formData.program_number.trim() || null,
                prosec: formData.prosec || null,
                prosec_authorization: formData.prosec_authorization.trim() || null,
                
                // Concatenar nombre completo del responsable si se desea guardar en 'responsible' también
                responsible: `${formData.responsible_name} ${formData.responsible_last_name}`.trim() || null,
                responsible_name: formData.responsible_name.trim() || null,
                responsible_last_name: formData.responsible_last_name.trim() || null,
                responsible_mother_last_name: formData.responsible_mother_last_name.trim() || null,
                responsible_rfc: formData.responsible_rfc.trim() || null,
                position: formData.position.trim() || null,
                
                manufacturer_id: formData.manufacturer_id.trim() || null,
                is_service_company: formData.is_service_company,
                order_format_type: formData.order_format_type.trim() || null,
                
                ctpat_svi: formData.ctpat_svi.trim() || null,
                trusted_exporter_number: formData.trusted_exporter_number.trim() || null
            };  

            let response;
            if (isEdit && item) {
                response = await updateCompany(item.id, dataToSend);
            } else {
                response = await createCompany(dataToSend);
            }

            if (response.error) {
                throw new Error(response.error);
            }

            await companyStore.loadCompanies();
            open = false;
            if (onSuccess) onSuccess();
        } catch (e) {
            error = e instanceof Error ? e.message : 'Error al guardar';
        } finally {
            loading = false;
        }
    }
</script>

<Dialog.Root bind:open>
    <Dialog.Content class="max-w-2xl max-h-[90vh] overflow-y-auto">
        <Dialog.Header>
            <Dialog.Title>{title}</Dialog.Title>
        </Dialog.Header>

        <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-4">
            {#if error}
                <div class="p-3 text-sm text-red-600 bg-red-50 rounded-md border border-red-200">
                    {error}
                </div>
            {/if}

            <Tabs.Root value="general" class="w-full">
                <Tabs.List class="grid w-full grid-cols-4">
                    <Tabs.Trigger value="general">General</Tabs.Trigger>
                    <Tabs.Trigger value="programas">Programas</Tabs.Trigger>
                    <Tabs.Trigger value="responsable">Responsable</Tabs.Trigger>
                    <Tabs.Trigger value="config">Config</Tabs.Trigger>
                </Tabs.List>

                <Tabs.Content value="general" class="space-y-4 py-4">
                    <div class="grid gap-2">
                        <Label for="name">Razón Social <span class="text-destructive">*</span></Label>
                        <Input id="name" bind:value={formData.name} placeholder="Nombre de la empresa" />
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="rfc">RFC <span class="text-destructive">*</span></Label>
                            <Input id="rfc" bind:value={formData.rfc} maxlength={13} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="curp">CURP</Label>
                            <Input id="curp" bind:value={formData.curp} maxlength={18} />
                        </div>
                    </div>

                    <div class="grid gap-2">
                        <Label for="main_activity">Actividad Principal</Label>
                        <Input id="main_activity" bind:value={formData.main_activity} />
                    </div>
                </Tabs.Content>

                <Tabs.Content value="programas" class="space-y-4 py-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="program">Programa (IMMEX)</Label>
                            <Input id="program" bind:value={formData.program} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="program_number">No. Programa</Label>
                            <Input id="program_number" bind:value={formData.program_number} />
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="prosec">Sector PROSEC (ID)</Label>
                            <Input id="prosec" type="number" bind:value={formData.prosec} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="prosec_auth">Autorización PROSEC</Label>
                            <Input id="prosec_auth" bind:value={formData.prosec_authorization} />
                        </div>
                    </div>
                </Tabs.Content>

                <Tabs.Content value="responsable" class="space-y-4 py-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="resp_name">Nombre</Label>
                            <Input id="resp_name" bind:value={formData.responsible_name} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="resp_last">Apellido Paterno</Label>
                            <Input id="resp_last" bind:value={formData.responsible_last_name} />
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="resp_mother">Apellido Materno</Label>
                            <Input id="resp_mother" bind:value={formData.responsible_mother_last_name} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="resp_rfc">RFC Responsable</Label>
                            <Input id="resp_rfc" bind:value={formData.responsible_rfc} maxlength={13} />
                        </div>
                    </div>
                    <div class="grid gap-2">
                        <Label for="position">Puesto / Cargo</Label>
                        <Input id="position" bind:value={formData.position} />
                    </div>
                </Tabs.Content>

                <Tabs.Content value="config" class="space-y-4 py-4">
                    <div class="grid grid-cols-2 gap-6">
                        <div class="flex items-center space-x-2">
                            <Switch id="service" bind:checked={formData.is_service_company} />
                            <Label for="service">Es Empresa de Servicios</Label>
                        </div>
                    </div>
                    
                    <div class="border-t my-2"></div>
                    
                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="man_id">Manufacturer ID (MID)</Label>
                            <Input id="man_id" bind:value={formData.manufacturer_id} />
                        </div>
                         <div class="grid gap-2">
                            <Label for="order_format">Formato de Pedido</Label>
                            <Input id="order_format" bind:value={formData.order_format_type} />
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div class="grid gap-2">
                            <Label for="ctpat">C-TPAT / SVI</Label>
                            <Input id="ctpat" bind:value={formData.ctpat_svi} />
                        </div>
                        <div class="grid gap-2">
                            <Label for="exporter">No. Exportador Confiable</Label>
                            <Input id="exporter" bind:value={formData.trusted_exporter_number} />
                        </div>
                    </div>
                </Tabs.Content>
            </Tabs.Root>

            <Dialog.Footer>
                <Button type="button" variant="outline" onclick={() => open = false}>Cancelar</Button>
                <Button type="submit" disabled={loading}>
                    {loading ? 'Guardando...' : 'Guardar Empresa'}
                </Button>
            </Dialog.Footer>
        </form>
    </Dialog.Content>
</Dialog.Root>