<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Label } from '$lib/components/ui/label';
	import { Input } from '$lib/components/ui/input';
	import { LoaderCircle, Save, FileText, Eye, DollarSign, Truck, Package } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { Select, SelectContent, SelectItem, SelectTrigger } from '$lib/components/ui/select';
	// Import Form Components
	import GeneralTabForm from '$lib/components/dashboard/invoices/edit/general-tab-form.svelte';
	import ObservationsTabForm from '$lib/components/dashboard/invoices/edit/observations-tab-form.svelte';
	import ItemsTabForm from '$lib/components/dashboard/invoices/edit/items/items-tab-form.svelte';
	import OthersTabForm from '$lib/components/dashboard/invoices/edit/others-tab-form.svelte';
	import InvoiceTopFields from '$lib/components/dashboard/invoices/edit/invoice-top-fields.svelte';
	import ContinuationTabForm from '$lib/components/dashboard/invoices/edit/continuation-tab-form.svelte';

	// Props
	let { data } = $props();

	// State
	let selectedInvoiceType = $state<string>('');
	let selectedOperationType = $state<string>('');
	let isLoading = $state(false);
	let isSaving = $state(false);
	let activeTab = $state('general');
	let companyStore: any = $state(undefined);

	// Form Data State
	let InvoiceTopFieldsFormData = $state<any>({});
	let generalFormData = $state<any>({});
	let observationFormData = $state<any>({});
	let itemsFormData = $state<any>({});
	let othersFormData = $state<any>({
		comments_status: '',
		transport_mode: 'TRUCK',
		is_mixed: null,
		print_stamp: false,
		rule_3121_parties_ii: false,
		related_doc_id: null,
		code_signature: '',
		electronic_signature: '',
		mandatory_person: '',
		contingency_mode: false,
		cove: '',
		operation_num: '',
		adendas: '',
		observations_vu: '',
		certified_number: ''
	});
	let continuationFormData = $state<any>({
		numero_tipo_transporte: '',
		es_ferrocarril: 'no',
		numero_bl: '',
		cantidad_guias_embarque: null,
		destino_origen: '',
		puerto_entrada: '',
		fue_revisado_equipo: false,
		sub_division: false,
		funge_como_cd: false,
		llego_pedimento: false,
		errores_facturacion: [],
		semaforo_verde_aduana_mexicana: false,
		semaforo_verde_aduana_americana: false,
		semaforo_rojo_aduana_mexicana: false,
		semaforo_rojo_aduana_americana: false
	});

	// Dummy objects for components
	let invoice = $state<any>({
		financials: { exchange_rate: 0 }
	});

	// Existence flags (not strictly needed for settings but required by components)
	let observationExists = $state(false);
	let itemsExists = $state(false);
	let othersExists = $state(false);
	let continuationExists = $state(false);

	const operationTypes = [
		{ value: 'imp', label: 'Importación' },
		{ value: 'exp', label: 'Exportación' }
	];

	onMount(async () => {
		try {
			const companyStoreModule = await import('$lib/stores/company.svelte');
			companyStore = companyStoreModule.companyStore;
		} catch (err) {
			console.error('Error loading company store:', err);
		}
	});

	async function loadSettings() {
		if (!selectedInvoiceType || !selectedOperationType || !companyStore?.activeCompany?.id) return;

		isLoading = true;
		try {
			const token = $page.data.user?.token;
			const headers: HeadersInit = {
				'Content-Type': 'application/json'
			};
			if (token) {
				headers['Authorization'] = `Bearer ${token}`;
			}

			const res = await fetch(
				`/api/v1/a76/invoice-settings/${selectedInvoiceType}?operation_type=${selectedOperationType}&company_id=${companyStore.activeCompany.id}`,
				{ headers }
			);

			if (res.ok) {
				const settingsData = await res.json();
				if (settingsData && settingsData.settings) {
					applySettings(settingsData.settings);
				} else {
					resetForms();
				}
			} else {
				resetForms();
			}
		} catch (error) {
			console.error('Error loading settings', error);
			resetForms();
		} finally {
			isLoading = false;
		}
	}

	function applySettings(settings: any) {
		InvoiceTopFieldsFormData = {
			is_pedimento_pending: false,
			pedimento_id: '',
			remesa: '',
			invoice_number: '',
			invoice_date: new Date().toISOString().split('T')[0],
			emission_date: new Date().toISOString().split('T')[0],
			operation_type: selectedOperationType,
			invoice_type: selectedInvoiceType,
			fecha_pedimento_del: '',
			fecha_pedimento_al: '',
			clave_pedimento: '',
			regimen_pedimento: '',
			...(settings.InvoiceTopFieldsFormData || {})
		};
		generalFormData = {
			provider_header: 'proveedor',
			provider_id: null,
			sold_to_header: 'consignado_a',
			sold_to_id: null,
			shipped_to_header: 'enviado_a',
			shipped_to_id: null,
			customs_broker_id: null,
			customs_broker_us_id: null,
			currency_type: '',
			currency: 'foreign',
			exchange_rate: null,
			weight_type: 'kgs',
			iva_factor: null,
			carrier_id: null,
			transport_id: '',
			driver_name: '',
			transport_type: '',
			transport_num: '',
			aduana: '',
			document_type: '',
			...(settings.generalFormData || {})
		};
		observationFormData = {
			observation_es: '',
			observation_en: '',
			freight: null,
			insurance_value: null,
			insurance: null,
			packaging: null,
			other_increments: null,
			total_increments_mn: null,
			total_increments_me: null,
			incoterm: null,
			enclosure: null,
			num_seals: null,
			movement_type: '',
			alternate_invoice: '',
			valuation_method: null,
			...(settings.observationFormData || {})
		};
		itemsFormData = settings.itemsFormData || {};
		othersFormData = {
			comments_status: '',
			transport_mode: 'TRUCK',
			is_mixed: null,
			print_stamp: false,
			rule_3121_parties_ii: false,
			related_doc_id: null,
			code_signature: '',
			electronic_signature: '',
			mandatory_person: '',
			contingency_mode: false,
			cove: '',
			operation_num: '',
			adendas: '',
			observations_vu: '',
			certified_number: '',
			...(settings.othersFormData || {})
		};
		continuationFormData = {
			numero_tipo_transporte: '',
			es_ferrocarril: 'no',
			numero_bl: '',
			cantidad_guias_embarque: null,
			destino_origen: '',
			puerto_entrada: '',
			fue_revisado_equipo: false,
			sub_division: false,
			funge_como_cd: false,
			llego_pedimento: false,
			errores_facturacion: [],
			semaforo_verde_aduana_mexicana: false,
			semaforo_verde_aduana_americana: false,
			semaforo_rojo_aduana_mexicana: false,
			semaforo_rojo_aduana_americana: false,
			...(settings.continuationFormData || {})
		};

		// Update the 'invoice' dummy object to reflect some top fields if needed for display
		invoice = {
			...invoice,
			...InvoiceTopFieldsFormData,
			operation_type: selectedOperationType,
			invoice_type: selectedInvoiceType
		};
	}

	function resetForms() {
		InvoiceTopFieldsFormData = {
			is_pedimento_pending: false,
			pedimento_id: '',
			remesa: '',
			invoice_number: '',
			invoice_date: new Date().toISOString().split('T')[0],
			emission_date: new Date().toISOString().split('T')[0],
			operation_type: selectedOperationType,
			invoice_type: selectedInvoiceType,
			fecha_pedimento_del: '',
			fecha_pedimento_al: '',
			clave_pedimento: '',
			regimen_pedimento: ''
		};
		generalFormData = {
			provider_header: 'proveedor',
			provider_id: null,
			sold_to_header: 'consignado_a',
			sold_to_id: null,
			shipped_to_header: 'enviado_a',
			shipped_to_id: null,
			customs_broker_id: null,
			customs_broker_us_id: null,
			currency_type: '',
			currency: 'foreign',
			exchange_rate: null,
			weight_type: 'kgs',
			iva_factor: null,
			carrier_id: null,
			transport_id: '',
			driver_name: '',
			transport_type: '',
			transport_num: '',
			aduana: '',
			document_type: ''
		};
		observationFormData = {
			observation_es: '',
			observation_en: '',
			freight: null,
			insurance_value: null,
			insurance: null,
			packaging: null,
			other_increments: null,
			total_increments_mn: null,
			total_increments_me: null,
			incoterm: null,
			enclosure: null,
			num_seals: null,
			movement_type: '',
			alternate_invoice: '',
			valuation_method: null
		};
		itemsFormData = {};
		othersFormData = {
			comments_status: '',
			transport_mode: 'TRUCK',
			is_mixed: null,
			print_stamp: false,
			rule_3121_parties_ii: false,
			related_doc_id: null,
			code_signature: '',
			electronic_signature: '',
			mandatory_person: '',
			contingency_mode: false,
			cove: '',
			operation_num: '',
			adendas: '',
			observations_vu: '',
			certified_number: ''
		};
		continuationFormData = {
			numero_tipo_transporte: '',
			es_ferrocarril: 'no',
			numero_bl: '',
			cantidad_guias_embarque: null,
			destino_origen: '',
			puerto_entrada: '',
			fue_revisado_equipo: false,
			sub_division: false,
			funge_como_cd: false,
			llego_pedimento: false,
			errores_facturacion: [],
			semaforo_verde_aduana_mexicana: false,
			semaforo_verde_aduana_americana: false,
			semaforo_rojo_aduana_mexicana: false,
			semaforo_rojo_aduana_americana: false
		};
		invoice = { financials: { exchange_rate: 0 } };
	}

	function cleanObject(obj: any): any {
		if (Array.isArray(obj)) {
			return obj.map(cleanObject).filter((v) => v !== null && v !== undefined && v !== '');
		}
		if (obj !== null && typeof obj === 'object') {
			return Object.entries(obj).reduce((acc: any, [key, value]) => {
				const cleaned = cleanObject(value);
				if (
					cleaned !== null &&
					cleaned !== undefined &&
					cleaned !== '' &&
					!(typeof cleaned === 'object' && Object.keys(cleaned).length === 0)
				) {
					acc[key] = cleaned;
				}
				return acc;
			}, {});
		}
		return obj;
	}

	async function handleSaveSettings() {
		if (!selectedInvoiceType || !selectedOperationType || !companyStore?.activeCompany?.id) {
			toast.error('Por favor selecciona tipo de factura y operación');
			return;
		}

		isSaving = true;

		// Use snaphot to get clean data from Svelte 5 proxies
		const rawSettings = {
			InvoiceTopFieldsFormData: $state.snapshot(InvoiceTopFieldsFormData),
			generalFormData: $state.snapshot(generalFormData),
			observationFormData: $state.snapshot(observationFormData),
			itemsFormData: $state.snapshot(itemsFormData),
			othersFormData: $state.snapshot(othersFormData),
			continuationFormData: $state.snapshot(continuationFormData)
		};

		// Clean the settings to only save what's configured
		const cleanedSettings = cleanObject(rawSettings);

		const settingsPayload = {
			invoice_type: selectedInvoiceType,
			operation_type: selectedOperationType,
			settings: cleanedSettings
		};

		try {
			const token = $page.data.user?.token;
			const headers: HeadersInit = {
				'Content-Type': 'application/json'
			};
			if (token) {
				headers['Authorization'] = `Bearer ${token}`;
			}

			const response = await fetch(
				`/api/v1/a76/invoice-settings/?company_id=${companyStore.activeCompany.id}`,
				{
					method: 'PUT',
					headers,
					body: JSON.stringify(settingsPayload)
				}
			);

			if (response.ok) {
				toast.success('Configuración guardada correctamente.');
			} else {
				const errorData = await response.json().catch(() => ({}));
				console.error('Save error details:', errorData);
				toast.error('Error al guardar la configuración.');
			}
		} catch (error) {
			console.error('Error saving settings:', error);
			toast.error('Ocurrió un error al guardar.');
		} finally {
			isSaving = false;
		}
	}

	// Watch for selection changes
	$effect(() => {
		if (selectedInvoiceType && selectedOperationType && companyStore?.activeCompany?.id) {
			loadSettings();
		}
	});
</script>

<div class="container mx-auto py-6 pb-32">
	<!-- Added padding bottom for footer -->
	<div class="mb-6 flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Configuración de Facturas</h1>
			<p class="text-muted-foreground">
				Define los valores predeterminados para la creación de facturas.
			</p>
		</div>
	</div>

	<Card.Root class="mb-6">
		<Card.Header>
			<Card.Title>Contexto de Configuración</Card.Title>
			<Card.Description
				>Selecciona el contexto para editar sus valores por defecto.</Card.Description
			>
		</Card.Header>
		<Card.Content class="flex gap-4">
			<div class="w-[250px]">
				<Label>Tipo de Operación</Label>
				<Select type="single" bind:value={selectedOperationType}>
					<SelectTrigger>
						{operationTypes.find((t) => t.value === selectedOperationType)?.label ||
							'Seleccionar...'}
					</SelectTrigger>
					<SelectContent>
						{#each operationTypes as type}
							<SelectItem value={type.value}>{type.label}</SelectItem>
						{/each}
					</SelectContent>
				</Select>
			</div>

			<div class="w-[350px]">
				<Label>Tipo de Factura</Label>
				<Select type="single" bind:value={selectedInvoiceType}>
					<SelectTrigger>
						{@const type = data.invoiceTypes.find((t) => t.key === selectedInvoiceType)}
						{type ? `${type.key} - ${type.description}` : 'Seleccionar...'}
					</SelectTrigger>
					<SelectContent class="max-h-[300px]">
						{#each data.invoiceTypes as type}
							<SelectItem value={type.key}>{type.key} - {type.description}</SelectItem>
						{/each}
					</SelectContent>
				</Select>
			</div>
		</Card.Content>
	</Card.Root>

	{#if selectedInvoiceType && selectedOperationType}
		{#if isLoading}
			<div class="flex justify-center py-12">
				<LoaderCircle class="animate-spin h-8 w-8 text-primary" />
			</div>
		{:else}
			<div class="grid gap-6">
				<!-- Top Fields (Header) -->
				<div class="bg-background rounded-lg border p-4">
					<h3 class="font-medium mb-4">Encabezado</h3>
					<InvoiceTopFields
						{invoice}
						bind:formData={InvoiceTopFieldsFormData}
						invoiceTypes={data.invoiceTypes || []}
						pedimentos={data.pedimentos || []}
						defaultOperationType={selectedOperationType}
						defaultInvoiceType={selectedInvoiceType}
					/>
				</div>

				<!-- Tabs for detailed sections -->
				<Tabs.Root bind:value={activeTab}>
					<Tabs.List class="grid w-full grid-cols-5 bg-muted rounded-md p-1 mb-4">
						<Tabs.Trigger value="general">General</Tabs.Trigger>
						<Tabs.Trigger value="observations">Observaciones</Tabs.Trigger>
						<Tabs.Trigger value="items">Partidas</Tabs.Trigger>
						<Tabs.Trigger value="others">Otros</Tabs.Trigger>
						<Tabs.Trigger value="continuation">Continuación</Tabs.Trigger>
					</Tabs.List>

					<Tabs.Content value="general">
						<GeneralTabForm
							{invoice}
							bind:formData={generalFormData}
							invoiceTypes={data.invoiceTypes || []}
							customsBrokers={data.customsBrokers || []}
							clients={data.clients || []}
							providers={data.providers || []}
							currencyTypes={data.currencyTypes || []}
							transportTypes={data.transportTypes || []}
							transporters={data.transporters || []}
							vehicles={data.vehicles || []}
							drivers={data.drivers || []}
							trailers={data.trailers || []}
							customsSections={data.customsSections || []}
							codePedimentoRegimens={data.codePedimentoRegimens || []}
							operationType={selectedOperationType === 'exp' ? 1 : 2}
							exchangeRate={0}
						/>
					</Tabs.Content>

					<Tabs.Content value="observations">
						<ObservationsTabForm
							{invoice}
							bind:formData={observationFormData}
							bind:exists={observationExists}
							seals={[]}
							incoterms={data.incoterms || []}
							enclosure={[]}
						/>
					</Tabs.Content>

					<Tabs.Content value="items">
						<div class="p-4 border rounded bg-muted/20 text-center">
							<p class="text-sm text-muted-foreground">
								La configuración predeterminada de partidas es limitada.
							</p>
						</div>
					</Tabs.Content>

					<Tabs.Content value="others">
						<OthersTabForm
							{invoice}
							bind:formData={othersFormData}
							bind:exists={othersExists}
							transportModes={data.transportModes || []}
						/>
					</Tabs.Content>

					<Tabs.Content value="continuation">
						<ContinuationTabForm
							{invoice}
							bind:formData={continuationFormData}
							bind:exists={continuationExists}
						/>
					</Tabs.Content>
				</Tabs.Root>
			</div>
		{/if}
	{:else}
		<div
			class="flex flex-col items-center justify-center border-2 border-dashed rounded-lg p-12 text-muted-foreground"
		>
			<FileText class="h-10 w-10 mb-2 opacity-20" />
			<p>Selecciona un tipo de operación y factura para comenzar.</p>
		</div>
	{/if}
</div>

<!-- Sticky Footer -->
<div
	class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur border-t shadow-lg z-10 p-4 transition-all duration-300 group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]"
>
	<div class="container mx-auto max-w-[1400px] flex justify-end gap-3">
		<Button variant="outline" onclick={resetForms} disabled={isSaving || !selectedInvoiceType}>
			Restablecer
		</Button>
		<Button onclick={handleSaveSettings} disabled={isSaving || !selectedInvoiceType}>
			{#if isSaving}
				<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
				Guardando...
			{:else}
				<Save class="mr-2 h-4 w-4" />
				Guardar Configuración
			{/if}
		</Button>
	</div>
</div>
