<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 ManifestCreate } from '$lib/api/dashboard/a76/manifests';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

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

	let loading = $state(false);
	let formData = $state<ManifestCreate>({
		manifest_number: '',
		carrier_code: '',
		entry_date: undefined,
		status: 'PENDIENTE',
		description: '',
		broker_code: '',
		person_in_charge: '',
		consigned_to: '',
		sent_by: '',
		foreign_exit_port: '',
		destination_port: '',
		entry_port: '',
		net_weight: 0,
		gross_weight: 0,
		total_value: 0
	});

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

		try {
			loading = true;
			if (!formData.manifest_number) {
				toast.error('El número de manifiesto es obligatorio');
				return;
			}

			const response = await manifestApi.create(companyStore.activeCompany.id.toString(), formData);
			if (response.error) {
				toast.error(response.error);
				return;
			}
			toast.success('Manifiesto creado correctamente');
			open = false;
			onSuccess?.();
		} catch (error) {
			console.error(error);
			toast.error('Error al crear 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>Nuevo Manifiesto</Dialog.Title>
			<Dialog.Description>
				Ingresa los datos generales del nuevo manifiesto de exportación.
			</Dialog.Description>
		</Dialog.Header>

		<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="manifest_number">Número de Manifiesto *</Label>
						<Input
							id="manifest_number"
							bind:value={formData.manifest_number}
							placeholder="Ej. MAN-2024-001"
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="entry_date">Fecha de Entrada (YYYYMMDD)</Label>
						<Input
							id="entry_date"
							type="number"
							bind:value={formData.entry_date}
							placeholder="YYYYMMDD"
							disabled={loading}
						/>
					</div>
				</div>
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="carrier_code">Código Transportista</Label>
						<Input
							id="carrier_code"
							bind:value={formData.carrier_code}
							placeholder="Ej. TR123"
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="broker_code">Código Broker</Label>
						<Input
							id="broker_code"
							bind:value={formData.broker_code}
							placeholder="Ej. BK456"
							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="entry_port">Puerto Arribo</Label>
						<Input id="entry_port" bind:value={formData.entry_port} disabled={loading} />
					</div>
					<div class="space-y-2">
						<Label for="foreign_exit_port">Puerto Salida (Ext)</Label>
						<Input
							id="foreign_exit_port"
							bind:value={formData.foreign_exit_port}
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="destination_port">Puerto Destino</Label>
						<Input
							id="destination_port"
							bind:value={formData.destination_port}
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<Separator />

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

		<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}
					Crear Manifiesto
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
