<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Loader2, Search, Plus, ArrowLeft } from 'lucide-svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		getLocations,
		createLocation,
		type Location,
		type LocationSystem
	} from '$lib/api/dashboard/a76/general_catalogs/locations';
	import { m } from '$lib/i18n/messages';

	let {
		open = $bindable(false),
		system = 'fixed_asset' as LocationSystem,
		onSelect,
		onClear
	}: {
		open: boolean;
		system?: LocationSystem;
		onSelect: (location: Location) => void;
		onClear?: () => void;
	} = $props();

	let locations: Location[] = $state([]);
	let filtered: Location[] = $state([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let error = $state('');
	let showRegisterForm = $state(false);

	// Register form state
	let formData = $state({
		clave_localizacion: '',
		localizacion: '',
		department: '',
		responsible: '',
		observations: ''
	});
	let formLoading = $state(false);
	let formError = $state('');

	async function loadLocations() {
		const companyId = companyStore?.activeCompany?.id;
		if (!companyId) {
			error = m.invoice_selectors_location_no_company_selected();
			return;
		}
		loading = true;
		error = '';
		try {
			const res = await getLocations(companyId, {
				system,
				page_size: 500
			});
			locations = res.items ?? [];
			filtered = locations;
		} catch (e) {
			error = m.invoice_selectors_location_load_error();
			console.error(e);
			locations = [];
			filtered = [];
		} finally {
			loading = false;
		}
	}

	function applyFilter() {
		if (!searchTerm.trim()) {
			filtered = locations;
		} else {
			const t = searchTerm.toLowerCase();
			filtered = locations.filter(
				(loc) =>
					(loc.clave_localizacion ?? '').toLowerCase().includes(t) ||
					(loc.localizacion ?? '').toLowerCase().includes(t)
			);
		}
	}

	function handleSelect(loc: Location) {
		onSelect(loc);
		open = false;
	}

	function handleRowKeydown(event: KeyboardEvent, loc: Location) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			handleSelect(loc);
		}
	}

	function openRegisterForm() {
		showRegisterForm = true;
		formData = {
			clave_localizacion: '',
			localizacion: '',
			department: '',
			responsible: '',
			observations: ''
		};
		formError = '';
	}

	function closeRegisterForm() {
		showRegisterForm = false;
		formError = '';
	}

	async function handleRegisterSubmit() {
		const companyId = companyStore?.activeCompany?.id;
		if (!companyId) {
			formError = m.invoice_selectors_location_no_company_selected();
			return;
		}
		if (!formData.clave_localizacion.trim()) {
			formError = m.invoice_selectors_location_required_key();
			return;
		}
		formLoading = true;
		formError = '';
		try {
			const created = await createLocation(
				{
					clave_localizacion: formData.clave_localizacion.trim(),
					localizacion: formData.localizacion?.trim() || null,
					system,
					department: formData.department?.trim() || null,
					responsible: formData.responsible?.trim() || null,
					observations: formData.observations?.trim() || null
				},
				companyId
			);
			onSelect(created);
			open = false;
		} catch (e) {
			formError = e instanceof Error ? e.message : m.invoice_selectors_location_save_error();
		} finally {
			formLoading = false;
		}
	}

	$effect(() => {
		if (open && !showRegisterForm) loadLocations();
	});

	$effect(() => {
		searchTerm;
		applyFilter();
	});

	$effect(() => {
		if (!open) showRegisterForm = false;
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="!max-w-[60vw] w-[60vw] max-h-[90vh] p-0 flex flex-col">
		<Dialog.Header class="px-6 py-4 border-b">
			<Dialog.Title class="text-lg font-semibold">{m.invoice_selectors_location_title()}</Dialog.Title>
		</Dialog.Header>

		{#if showRegisterForm}
			<!-- Registrar nueva ubicación (formulario) -->
			<form
				class="flex flex-col flex-1 overflow-hidden"
				onsubmit={(e) => {
					e.preventDefault();
					handleRegisterSubmit();
				}}
			>
				<div class="flex-1 overflow-auto px-6 py-4 space-y-4">
					{#if formError}
						<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
							{formError}
						</div>
					{/if}
					<div class="grid gap-4">
						<div class="grid grid-cols-4 items-center gap-4">
							<Label for="reg-clave" class="text-right">{m.invoice_selectors_location_key_label()}</Label>
							<div class="col-span-3">
								<Input
									id="reg-clave"
									bind:value={formData.clave_localizacion}
									maxlength={20}
									placeholder={m.invoice_selectors_location_key_placeholder()}
									class="h-9"
								/>
							</div>
						</div>
						<div class="grid grid-cols-4 items-center gap-4">
							<Label for="reg-localizacion" class="text-right">{m.invoice_selectors_location_location_label()}</Label>
							<div class="col-span-3">
								<Input
									id="reg-localizacion"
									bind:value={formData.localizacion}
									maxlength={200}
									placeholder={m.invoice_selectors_location_location_placeholder()}
									class="h-9"
								/>
							</div>
						</div>
						<div class="grid grid-cols-4 items-center gap-4">
							<Label for="reg-department" class="text-right">{m.invoice_selectors_location_department_label()}</Label>
							<div class="col-span-3">
								<Input
									id="reg-department"
									bind:value={formData.department}
									maxlength={100}
									placeholder={m.invoice_selectors_location_optional_placeholder()}
									class="h-9"
								/>
							</div>
						</div>
						<div class="grid grid-cols-4 items-center gap-4">
							<Label for="reg-responsible" class="text-right">{m.invoice_selectors_location_responsible_label()}</Label>
							<div class="col-span-3">
								<Input
									id="reg-responsible"
									bind:value={formData.responsible}
									maxlength={200}
									placeholder={m.invoice_selectors_location_optional_placeholder()}
									class="h-9"
								/>
							</div>
						</div>
						<div class="grid grid-cols-4 items-center gap-4">
							<Label for="reg-observations" class="text-right">{m.invoice_selectors_location_observations_label()}</Label>
							<div class="col-span-3">
								<Input
									id="reg-observations"
									bind:value={formData.observations}
									placeholder={m.invoice_selectors_location_optional_placeholder()}
									class="h-9"
								/>
							</div>
						</div>
					</div>
				</div>
				<div class="px-6 py-4 border-t flex justify-end gap-2">
					<Button type="button" variant="outline" onclick={closeRegisterForm} disabled={formLoading}>
						<ArrowLeft class="mr-2 h-4 w-4" />
						{m.invoice_selectors_location_back_to_list()}
					</Button>
					<Button type="submit" disabled={formLoading}>
						{#if formLoading}
							<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						{/if}
						{m.invoice_selectors_location_save()}
					</Button>
				</div>
			</form>
		{:else}
			<!-- Listado + búsqueda -->
			<div class="px-6 py-3 border-b bg-zinc-50 dark:bg-zinc-900 flex items-center gap-2">
				<div class="flex items-center gap-2 flex-1">
					<Search class="w-4 h-4 text-zinc-400 shrink-0" />
					<Input
						bind:value={searchTerm}
						placeholder={m.invoice_selectors_location_search_placeholder()}
						class="flex-1 h-9"
					/>
				</div>
				<Button type="button" variant="default" size="sm" onclick={openRegisterForm}>
					<Plus class="mr-2 h-4 w-4" />
					{m.invoice_selectors_location_register_new()}
				</Button>
			</div>

			<div class="flex-1 overflow-auto px-6 py-4">
				{#if loading}
					<div class="flex items-center justify-center py-20">
						<Loader2 class="w-8 h-8 animate-spin text-zinc-900 dark:text-zinc-100" />
					</div>
				{:else if error}
					<div class="flex items-center justify-center py-20 text-red-600">
						<p>{error}</p>
					</div>
				{:else}
					<div class="border rounded-md overflow-hidden">
						<table class="w-full text-sm">
							<thead class="bg-zinc-900 dark:bg-zinc-800 text-white">
								<tr>
									<th class="px-3 py-2 text-left font-semibold border-r border-zinc-700">{m.invoice_selectors_location_column_key()}</th>
									<th class="px-3 py-2 text-left font-semibold">{m.invoice_selectors_location_column_location()}</th>
								</tr>
							</thead>
							<tbody>
								{#each filtered as loc}
									<tr
										class="border-b hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
										tabindex="0"
										onclick={() => handleSelect(loc)}
										onkeydown={(event) => handleRowKeydown(event, loc)}
									>
										<td class="px-3 py-2 border-r">{loc.clave_localizacion ?? '—'}</td>
										<td class="px-3 py-2">{loc.localizacion ?? '—'}</td>
									</tr>
								{/each}
								{#if filtered.length === 0}
									<tr>
										<td colspan="2" class="px-3 py-8 text-center text-zinc-500">
											{m.invoice_selectors_location_no_results()}
										</td>
									</tr>
								{/if}
							</tbody>
						</table>
					</div>
				{/if}
			</div>

			<div class="px-6 py-4 border-t flex justify-end gap-2">
				{#if onClear}
					<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
				{/if}
				<Button variant="outline" onclick={() => (open = false)}>{m.invoice_selectors_location_cancel()}</Button>
			</div>
		{/if}
	</Dialog.Content>
</Dialog.Root>
