<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 Select from '$lib/components/ui/select';
	import { driversApi, type Driver } from '$lib/api/dashboard/a76/drivers';
	import { transportersApi, type Transporter } from '$lib/api/dashboard/a76/transporters';
	import { companyStore } from '$lib/stores/company.svelte';

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

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Conductor' : 'Nuevo Conductor');

	let transporters = $state<Transporter[]>([]);
	let transportersLoading = $state(false);

	let formData = $state<Driver & { lineStr?: string }>({
		transporter_key: '',
		line: 0,
		driver_name: '',
		license_number: '',
		first_name: '',
		last_name: '',
		badge_number: '',
		express_line_id: '',
		ace_id: '',
		birth_country: '',
		hazardous_material_auth: '',
		hazardous_material_state: '',
		class_type: ''
	});

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

	// Cargar transportistas al abrir el diálogo en modo creación (backend max page_size=100)
	$effect(() => {
		if (open && !item && companyStore.activeCompany) {
			transportersLoading = true;
			transportersApi
				.list(companyStore.activeCompany.id, { page: 1, page_size: 100 })
				.then((res) => {
					if (res.data?.items) transporters = res.data.items;
					else transporters = [];
				})
				.catch(() => (transporters = []))
				.finally(() => (transportersLoading = false));
		}
	});

	$effect(() => {
		if (item) {
			formData = {
				...item,
				lineStr: String(item.line)
			};
		} else {
			formData = {
				transporter_key: '',
				line: 0,
				lineStr: '',
				driver_name: '',
				license_number: '',
				first_name: '',
				last_name: '',
				badge_number: '',
				express_line_id: '',
				ace_id: '',
				birth_country: '',
				hazardous_material_auth: '',
				hazardous_material_state: '',
				class_type: ''
			};
		}
	});

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

		try {
			const company = companyStore.activeCompany;
			if (!company) {
				throw new Error('No hay una compañía seleccionada');
			}

			if (!formData.transporter_key?.trim()) {
				throw new Error('Selecciona un transportista de la lista');
			}

			const lineNum = isEdit ? item!.line : parseInt(String(formData.lineStr ?? formData.line), 10);
			if (!isEdit && (Number.isNaN(lineNum) || lineNum < 1)) {
				throw new Error('La línea debe ser un número mayor a 0');
			}

			if (isEdit && item) {
				const response = await driversApi.update(
					item.transporter_key,
					item.line,
					{
						driver_name: formData.driver_name || undefined,
						license_number: formData.license_number || undefined,
						first_name: formData.first_name || undefined,
						last_name: formData.last_name || undefined,
						badge_number: formData.badge_number || undefined,
						express_line_id: formData.express_line_id || undefined,
						ace_id: formData.ace_id || undefined,
						birth_country: formData.birth_country || undefined,
						hazardous_material_auth: formData.hazardous_material_auth || undefined,
						hazardous_material_state: formData.hazardous_material_state || undefined,
						class_type: formData.class_type || undefined
					},
					company.id
				);
				if (response.error) throw new Error(response.error);
			} else {
				const payload = {
					transporter_key: String(formData.transporter_key).trim(),
					line: lineNum,
					driver_name: formData.driver_name || undefined,
					license_number: formData.license_number || undefined,
					first_name: formData.first_name || undefined,
					last_name: formData.last_name || undefined,
					badge_number: formData.badge_number || undefined,
					express_line_id: formData.express_line_id || undefined,
					ace_id: formData.ace_id || undefined,
					birth_country: formData.birth_country || undefined,
					hazardous_material_auth: formData.hazardous_material_auth || undefined,
					hazardous_material_state: formData.hazardous_material_state || undefined,
					class_type: formData.class_type || undefined,
					company_id: company.id,
					tenant_id: company.tenant_id
				};
				const response = await driversApi.create(payload, company.id);
				if (response.error) throw new Error(response.error);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			if (e && typeof e === 'object' && 'message' in e) {
				error = (e as { message: string }).message;
			} else {
				error = 'Error al guardar el conductor';
			}
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		open = false;
		error = null;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit
					? 'Modifica los datos del conductor'
					: 'Completa los datos para crear un nuevo conductor'}
			</Dialog.Description>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="space-y-6"
		>
			{#if error}
				<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
				<div class="grid gap-2">
					<Label for="transporter_key"
						>Transportista <span class="text-destructive">*</span></Label
					>
					{#if isEdit}
						<Input
							id="transporter_key"
							value={formData.transporter_key}
							disabled
							class="bg-muted"
						/>
					{:else}
						<Select.Root
							type="single"
							bind:value={formData.transporter_key}
							disabled={transportersLoading}
						>
							<Select.Trigger class="w-full">
								{transportersLoading
									? 'Cargando transportistas...'
									: transporters.length === 0
										? 'No hay transportistas'
										: transporters.find((t) => t.transporter_key === formData.transporter_key)
											? `${formData.transporter_key} - ${transporters.find((t) => t.transporter_key === formData.transporter_key)?.name || ''}`
											: 'Seleccionar transportista'}
							</Select.Trigger>
							<Select.Content>
								{#each transporters as t}
									<Select.Item value={t.transporter_key} label={t.transporter_key}>
										{t.transporter_key} — {t.name || t.short_name || 'Sin nombre'}
									</Select.Item>
								{/each}
								{#if !transportersLoading && transporters.length === 0}
									<div class="px-2 py-3 text-sm text-muted-foreground">
										No hay transportistas. Crea uno en el catálogo Transportistas.
									</div>
								{/if}
							</Select.Content>
						</Select.Root>
					{/if}
				</div>

				<div class="grid gap-2">
					<Label for="line">Línea <span class="text-destructive">*</span></Label>
					<Input
						id="line"
						type="number"
						min="1"
						bind:value={formData.lineStr}
						disabled={isEdit}
						required
						placeholder="Ej: 1"
					/>
				</div>

				<div class="grid gap-2 md:col-span-2">
					<Label for="driver_name">Nombre del Conductor</Label>
					<Input id="driver_name" bind:value={formData.driver_name} maxlength={80} />
				</div>

				<div class="grid gap-2">
					<Label for="first_name">Nombre</Label>
					<Input id="first_name" bind:value={formData.first_name} maxlength={20} />
				</div>

				<div class="grid gap-2">
					<Label for="last_name">Apellido</Label>
					<Input id="last_name" bind:value={formData.last_name} maxlength={20} />
				</div>

				<div class="grid gap-2">
					<Label for="license_number">Número de Licencia</Label>
					<Input id="license_number" bind:value={formData.license_number} maxlength={29} />
				</div>

				<div class="grid gap-2">
					<Label for="badge_number">Número de Placa/Insignia</Label>
					<Input id="badge_number" bind:value={formData.badge_number} maxlength={20} />
				</div>

				<div class="grid gap-2">
					<Label for="express_line_id">Express Line ID</Label>
					<Input id="express_line_id" bind:value={formData.express_line_id} maxlength={17} />
				</div>

				<div class="grid gap-2">
					<Label for="ace_id">ACE ID</Label>
					<Input id="ace_id" bind:value={formData.ace_id} maxlength={20} />
				</div>

				<div class="grid gap-2">
					<Label for="birth_country">País de Nacimiento</Label>
					<Input id="birth_country" bind:value={formData.birth_country} maxlength={3} placeholder="MEX / USA" />
				</div>

				<div class="grid gap-2">
					<Label for="hazardous_material_auth">Auth. Material Peligroso</Label>
					<Input id="hazardous_material_auth" bind:value={formData.hazardous_material_auth} maxlength={2} />
				</div>

				<div class="grid gap-2">
					<Label for="hazardous_material_state">Estado Material Peligroso</Label>
					<Input id="hazardous_material_state" bind:value={formData.hazardous_material_state} maxlength={30} />
				</div>

				<div class="grid gap-2">
					<Label for="class_type">Tipo de Clase</Label>
					<Input id="class_type" bind:value={formData.class_type} maxlength={1} />
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={handleCancel} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : isEdit ? 'Actualizar' : 'Crear'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
