<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 { Separator } from '$lib/components/ui/separator';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Loader2 } from 'lucide-svelte';
	import {
		manifestApi,
		type Manifest,
		type ManifestUpdate
	} from '$lib/api/dashboard/a76/manifests';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

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

	let loading = $state(false);
	let formData = $state<ManifestUpdate>({});

	$effect(() => {
		if (open && manifest) {
			formData = {
				manifest_number: manifest.manifest_number || '',
				carrier_code: manifest.carrier_code || '',
				entry_date: manifest.entry_date,
				status: manifest.status || 'PENDIENTE',
				description: manifest.description || '',
				broker_code: manifest.broker_code || '',
				person_in_charge: manifest.person_in_charge || '',
				consigned_to: manifest.consigned_to || '',
				sent_by: manifest.sent_by || '',
				foreign_exit_port: manifest.foreign_exit_port || '',
				destination_port: manifest.destination_port || '',
				entry_port: manifest.entry_port || '',
				net_weight: manifest.net_weight || 0,
				gross_weight: manifest.gross_weight || 0,
				total_value: manifest.total_value || 0
			};
		}
	});

	async function handleSubmit() {
		if (!manifest || !companyStore.activeCompany) return;

		try {
			loading = true;
			const response = await manifestApi.update(
				companyStore.activeCompany.id.toString(),
				manifest.id,
				formData
			);
			if (response.error) {
				toast.error(response.error);
				return;
			}
			toast.success('Manifiesto actualizado correctamente');
			open = false;
			onSuccess?.();
		} catch (error) {
			console.error(error);
			toast.error('Error al actualizar el manifiesto');
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-[700px]">
		<Dialog.Header>
			<Dialog.Title>Editar Manifiesto</Dialog.Title>
			<Dialog.Description>
				Modifica los datos del manifiesto <span class="font-mono font-semibold"
					>{manifest?.manifest_number}</span
				>.
			</Dialog.Description>
		</Dialog.Header>

		{#if manifest}
			<div class="grid gap-6 py-4">
				<div class="space-y-4">
					<h4 class="text-xs font-bold tracking-wider text-muted-foreground uppercase">
						Información General
					</h4>
					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="edit-manifest_number">Número de Manifiesto</Label>
							<Input
								id="edit-manifest_number"
								bind:value={formData.manifest_number}
								disabled={loading}
							/>
						</div>
						<div class="space-y-2">
							<Label for="edit-entry_date">Fecha de Entrada</Label>
							<Input
								id="edit-entry_date"
								type="number"
								bind:value={formData.entry_date}
								disabled={loading}
							/>
						</div>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="edit-carrier_code">Código Transportista</Label>
							<Input id="edit-carrier_code" bind:value={formData.carrier_code} disabled={loading} />
						</div>
						<div class="space-y-2">
							<Label for="edit-broker_code">Código Broker</Label>
							<Input id="edit-broker_code" bind:value={formData.broker_code} disabled={loading} />
						</div>
					</div>
				</div>

				<Separator />

				<div class="space-y-4">
					<h4 class="text-xs font-bold tracking-wider text-muted-foreground uppercase">
						Logística
					</h4>
					<div class="grid grid-cols-3 gap-4">
						<div class="space-y-2">
							<Label for="edit-entry_port">Puerto Arribo</Label>
							<Input id="edit-entry_port" bind:value={formData.entry_port} disabled={loading} />
						</div>
						<div class="space-y-2">
							<Label for="edit-foreign_exit_port">Puerto Salida (Ext)</Label>
							<Input
								id="edit-foreign_exit_port"
								bind:value={formData.foreign_exit_port}
								disabled={loading}
							/>
						</div>
						<div class="space-y-2">
							<Label for="edit-destination_port">Puerto Destino</Label>
							<Input
								id="edit-destination_port"
								bind:value={formData.destination_port}
								disabled={loading}
							/>
						</div>
					</div>
				</div>

				<Separator />

				<div class="space-y-2">
					<Label for="edit-description">Descripción</Label>
					<Textarea id="edit-description" bind:value={formData.description} disabled={loading} />
				</div>
			</div>
		{/if}

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)} disabled={loading}>Cancelar</Button>
			<Button onclick={handleSubmit} disabled={loading}>
				{#if loading}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Guardando
				{:else}
					Guardar Cambios
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
