<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import { Badge } from '$lib/components/ui/badge';
	import { fade, fly, slide, scale } from 'svelte/transition';
	import {
		Plus,
		Pencil,
		Trash2,
		Loader2,
		Users,
		User,
		MapPin,
		Search,
		Globe,
		FolderSearch,
		UserCheck,
		UserPlus,
		ArrowRight,
		CheckCircle2,
		Hash,
		Map,
		X,
		Save
	} from 'lucide-svelte';
	import * as Dialog from '$lib/components/ui/dialog';
	import { companyStore } from '$lib/stores/company.svelte';
	import { manifestDriversApi, type ManifestDriver } from '$lib/api/dashboard/a76/manifest-drivers';
	import { toast } from 'svelte-sonner';
	import DriverSelectorDialog from './modals/driver-selector-dialog.svelte';
	import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';

	let {
		manifestNumber,
		carrierName,
		isNewManifest
	}: {
		manifestNumber: string;
		carrierName: string;
		isNewManifest: boolean;
	} = $props();

	let drivers = $state<ManifestDriver[]>([]);
	let loading = $state(false);
	let showForm = $state(false);
	let saving = $state(false);

	let showDriverDialog = $state(false);
	let showCountryDialog = $state(false);

	let editingIndex = $state<number | null>(null);

	let formData = $state<Partial<ManifestDriver>>({
		driver_name: '',
		driver_type: 'C',
		address_1: '',
		address_2: '',
		city: '',
		state: '',
		postal_code: '',
		country: 'MEX'
	});

	let selectedCountryName = $state('México');

	const typeLabels: Record<string, { label: string; color: string; icon: any }> = {
		C: { label: 'Conductor', color: 'bg-primary/10 text-primary border-primary/20', icon: User },
		M: { label: 'Tripulación', color: 'bg-muted text-muted-foreground border-border', icon: Users },
		P: { label: 'Pasajero', color: 'bg-muted text-muted-foreground border-border', icon: UserCheck }
	};

	$effect(() => {
		if (manifestNumber && !isNewManifest && companyStore.activeCompany) {
			loadDrivers();
		}
	});

	async function loadDrivers() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const res = await manifestDriversApi.list(companyStore.activeCompany.id, manifestNumber);
			const data = (res as any).data || res;
			if (data && data.items) {
				drivers = data.items;
			}
		} catch (e) {
			console.error('Error loading manifest drivers:', e);
			toast.error('Error al cargar la tripulación');
		} finally {
			loading = false;
		}
	}

	function handleAdd() {
		if (!manifestNumber && isNewManifest) {
			toast.warning('Primero debe asignar un número de manifiesto');
			return;
		}
		editingIndex = null;
		formData = {
			manifest_number: manifestNumber,
			driver_name: '',
			driver_type: 'C',
			address_1: '',
			address_2: '',
			city: '',
			state: '',
			postal_code: '',
			country: 'MEX'
		};
		selectedCountryName = 'México';
		showForm = true;
	}

	function handleEdit(index: number) {
		editingIndex = index;
		const driver = drivers[index];
		formData = { ...driver };
		showForm = true;
	}

	function handleCancel() {
		showForm = false;
		editingIndex = null;
	}

	async function handleDelete(index: number) {
		const driver = drivers[index];
		if (!confirm(`¿Está seguro de eliminar a ${driver.driver_name}?`)) return;

		if (!companyStore.activeCompany) return;

		try {
			await manifestDriversApi.delete(
				driver.manifest_number,
				driver.driver_name,
				companyStore.activeCompany.id
			);
			toast.success('Miembro eliminado');
			if (showForm && editingIndex === index) handleCancel();
			loadDrivers();
		} catch (e) {
			console.error('Error deleting driver:', e);
			toast.error('Error al eliminar');
		}
	}

	async function handleSave() {
		if (!formData.driver_name) {
			toast.error('El nombre es obligatorio');
			return;
		}

		if (!companyStore.activeCompany) return;
		saving = true;

		try {
			const companyId = companyStore.activeCompany.id;
			const payload = {
				...formData,
				manifest_number: manifestNumber
			} as ManifestDriver;

			if (editingIndex !== null) {
				const original = drivers[editingIndex];
				await manifestDriversApi.update(
					original.manifest_number,
					original.driver_name,
					companyId,
					payload
				);
				toast.success('Actualizado correctamente');
			} else {
				await manifestDriversApi.create(companyId, payload);
				toast.success('Agregado correctamente');
			}
			showForm = false;
			loadDrivers();
		} catch (e) {
			console.error('Error saving driver:', e);
			toast.error('Error al guardar');
		} finally {
			saving = false;
		}
	}

	function handleDriverSelect(item: any) {
		formData.driver_name = item.driver_name;
		showDriverDialog = false;
	}

	function handleCountrySelect(item: any) {
		formData.country = item.m3_key;
		selectedCountryName = item.description_es;
		showCountryDialog = false;
	}
</script>

<div class="space-y-4">
	<!-- Main Table -->
	<Card.Root class="overflow-hidden border shadow-sm">
		<Card.Header class="border-b bg-muted/30 p-2 px-3">
			<div class="flex items-center justify-between">
				<div class="flex items-center gap-2">
					<div class="rounded-md bg-primary/10 p-1.5">
						<Users class="h-4 w-4 text-primary" />
					</div>
					<div>
						<Card.Title class="text-base font-bold tracking-tight">Tripulación</Card.Title>
						<Card.Description class="text-xs">Personal activo</Card.Description>
					</div>
				</div>
				<Button onclick={handleAdd} size="sm" class="h-7 gap-1.5 px-3 text-xs">
					<Plus class="h-3.5 w-3.5" />
					Nuevo
				</Button>
			</div>
		</Card.Header>
		<Card.Content class="p-0">
			<div class="min-h-[300px] overflow-x-auto">
				<table class="w-full text-left text-sm">
					<thead
						class="border-b bg-muted/50 text-xs font-bold tracking-wider text-muted-foreground uppercase"
					>
						<tr>
							<th class="px-4 py-2">Nombre</th>
							<th class="px-4 py-2">Tipo</th>
							<th class="px-4 py-2">Ubicación</th>
							<th class="w-[80px] px-4 py-2 text-right"></th>
						</tr>
					</thead>
					<tbody class="divide-y">
						{#if loading && drivers.length === 0}
							<tr>
								<td colspan="4" class="h-48 text-center text-muted-foreground">
									<Loader2 class="mx-auto mb-2 h-6 w-6 animate-spin opacity-50" />
									Cargando registros...
								</td>
							</tr>
						{:else if drivers.length === 0}
							<tr>
								<td colspan="4" class="h-48 text-center text-muted-foreground">
									No hay tripulación registrada en este manifiesto.
								</td>
							</tr>
						{:else}
							{#each drivers as driver, i}
								<tr
									class="group transition-colors hover:bg-muted/30 {editingIndex === i
										? 'bg-primary/5'
										: ''}"
								>
									<td class="px-4 py-2 text-sm font-medium">
										{driver.driver_name}
									</td>
									<td class="px-4 py-2">
										<Badge
											variant="outline"
											class="h-5 text-[10px] font-bold uppercase {typeLabels[
												driver.driver_type as keyof typeof typeLabels
											]?.color || ''}"
										>
											{typeLabels[driver.driver_type as keyof typeof typeLabels]?.label ||
												driver.driver_type}
										</Badge>
									</td>
									<td class="px-4 py-2 text-muted-foreground">
										<div class="flex items-center gap-1 text-xs">
											<MapPin class="h-3 w-3" />
											{driver.city || ''}, {driver.country || ''}
										</div>
									</td>
									<td class="px-4 py-2 text-right">
										<div class="flex justify-end gap-1">
											<Button
												variant="ghost"
												size="icon"
												class="h-7 w-7"
												onclick={() => handleEdit(i)}
											>
												<Pencil class="h-3 w-3" />
											</Button>
											<Button
												variant="ghost"
												size="icon"
												class="h-7 w-7 text-destructive"
												onclick={() => handleDelete(i)}
											>
												<Trash2 class="h-3 w-3" />
											</Button>
										</div>
									</td>
								</tr>
							{/each}
						{/if}
					</tbody>
				</table>
			</div>
		</Card.Content>
	</Card.Root>

	<!-- Member Form Dialog -->
	<Dialog.Root bind:open={showForm}>
		<Dialog.Content class="sm:max-w-[550px]">
			<Dialog.Header>
				<Dialog.Title class="flex items-center gap-2">
					<UserPlus class="h-5 w-5 text-primary" />
					{editingIndex !== null ? 'Editar' : 'Agregar'} Miembro de Tripulación
				</Dialog.Title>
				<Dialog.Description>
					Ingrese los detalles del personal para este manifiesto.
				</Dialog.Description>
			</Dialog.Header>

			<div class="grid gap-6 py-4">
				<!-- Name Section -->
				<div class="space-y-2">
					<Label class="text-xs font-bold tracking-wide uppercase">Nombre Completo</Label>
					<div class="flex gap-2">
						<Input
							value={formData.driver_name}
							placeholder="Seleccione del catálogo..."
							class="h-10 cursor-pointer bg-muted/30 text-sm"
							readonly
							onclick={() => (showDriverDialog = true)}
						/>
						<Button
							variant="outline"
							size="icon"
							class="h-10 w-10 shrink-0"
							onclick={() => (showDriverDialog = true)}
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<!-- Address Grid -->
				<div class="grid grid-cols-2 gap-4">
					<div class="col-span-2 space-y-2">
						<Label class="text-xs font-bold tracking-wide uppercase">Dirección Principal</Label>
						<Input
							bind:value={formData.address_1}
							placeholder="Calle, número..."
							class="h-10 text-sm"
						/>
					</div>
					<div class="space-y-2">
						<Label class="text-xs font-bold tracking-wide uppercase">Ciudad</Label>
						<Input bind:value={formData.city} placeholder="Ciudad..." class="h-10 text-sm" />
					</div>
					<div class="space-y-2">
						<Label class="text-xs font-bold tracking-wide uppercase">Estado</Label>
						<Input bind:value={formData.state} placeholder="Estado..." class="h-10 text-sm" />
					</div>
					<div class="space-y-2">
						<Label class="text-xs font-bold tracking-wide uppercase">CP</Label>
						<Input bind:value={formData.postal_code} placeholder="00000" class="h-10 text-sm" />
					</div>
					<div class="space-y-2">
						<Label class="text-xs font-bold tracking-wide uppercase">País</Label>
						<div class="flex gap-2">
							<Input
								value={selectedCountryName || formData.country}
								readonly
								class="h-10 bg-muted/30 text-sm"
								onclick={() => (showCountryDialog = true)}
							/>
							<Button
								variant="outline"
								size="icon"
								class="h-10 w-10 shrink-0"
								onclick={() => (showCountryDialog = true)}
							>
								<Globe class="h-4 w-4" />
							</Button>
						</div>
					</div>
				</div>

				<!-- Role Selection -->
				<div class="space-y-3 border-t pt-4">
					<Label class="text-xs font-bold tracking-wide uppercase">Rol en el viaje</Label>
					<RadioGroup.Root bind:value={formData.driver_type} class="grid grid-cols-3 gap-3">
						<label
							for="modal-r-cond"
							class="flex cursor-pointer flex-col items-center justify-center rounded-xl border p-3 py-4 transition-all hover:bg-muted/50 {formData.driver_type ===
							'C'
								? 'border-primary bg-primary/5 ring-1 ring-primary'
								: 'bg-muted/10'}"
						>
							<User
								class="mb-2 h-5 w-5 {formData.driver_type === 'C'
									? 'text-primary'
									: 'text-muted-foreground'}"
							/>
							<span class="text-xs font-bold">Conductor</span>
							<RadioGroup.Item value="C" id="modal-r-cond" class="sr-only" />
						</label>
						<label
							for="modal-r-miem"
							class="flex cursor-pointer flex-col items-center justify-center rounded-xl border p-3 py-4 transition-all hover:bg-muted/50 {formData.driver_type ===
							'M'
								? 'border-primary bg-primary/5 ring-1 ring-primary'
								: 'bg-muted/10'}"
						>
							<Users
								class="mb-2 h-5 w-5 {formData.driver_type === 'M'
									? 'text-primary'
									: 'text-muted-foreground'}"
							/>
							<span class="text-xs font-bold">Tripulante</span>
							<RadioGroup.Item value="M" id="modal-r-miem" class="sr-only" />
						</label>
						<label
							for="modal-r-pas"
							class="flex cursor-pointer flex-col items-center justify-center rounded-xl border p-3 py-4 transition-all hover:bg-muted/50 {formData.driver_type ===
							'P'
								? 'border-primary bg-primary/5 ring-1 ring-primary'
								: 'bg-muted/10'}"
						>
							<UserCheck
								class="mb-2 h-5 w-5 {formData.driver_type === 'P'
									? 'text-primary'
									: 'text-muted-foreground'}"
							/>
							<span class="text-xs font-bold">Pasajero</span>
							<RadioGroup.Item value="P" id="modal-r-pas" class="sr-only" />
						</label>
					</RadioGroup.Root>
				</div>
			</div>

			<Dialog.Footer class="gap-2 sm:gap-0">
				<Button variant="ghost" onclick={handleCancel} disabled={saving}>Cancelar</Button>
				<Button onclick={handleSave} disabled={saving} class="min-w-[120px] font-bold">
					{#if saving}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						Guardando...
					{:else}
						<Save class="mr-2 h-4 w-4" />
						Guardar cambios
					{/if}
				</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>
</div>

<DriverSelectorDialog bind:open={showDriverDialog} onSelect={handleDriverSelect} />
<CountrySelectorDialog bind:open={showCountryDialog} onSelect={handleCountrySelect} />
