<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 { clientsProvidersApi, type ClientProvider, type CreateClientProviderData, type UpdateClientProviderData } from "$lib/api/dashboard/a76/clients-providers";
	import { companyStore } from "$lib/stores/company.svelte";
	import { LoaderCircle } from 'lucide-svelte';

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

	let formData = $state({
		rfc: "",
		name: "",
		curp: "",
		type_nat_foreign: "N",
		client_or_provider: "client",
		is_active: true,
		// Address fields
		streets: "",
		exterior_number: "",
		interior_number: "",
		neighborhood: "",
		municipality: "",
		city: "",
		state: "",
		country: "",
		postal_code: "",
		email: "",
		phone: "",
		contact: "",
		// Programs fields (subset)
		program: "",
		program_number: "",
		manufacturer_id: ""
	});

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

	// Actualizar formData cuando item cambia
	$effect(() => {
		if (item) {
			formData = {
				rfc: item.rfc,
				name: item.name,
				curp: item.curp || "",
				type_nat_foreign: item.type_nat_foreign || "N",
				client_or_provider: item.client_or_provider || "client",
				is_active: item.is_active ?? true,
				streets: item.address?.streets || "",
				exterior_number: item.address?.exterior_number || "",
				interior_number: item.address?.interior_number || "",
				neighborhood: item.address?.neighborhood || "",
				municipality: item.address?.municipality || "",
				city: item.address?.city || "",
				state: item.address?.state || "",
				country: item.address?.country || "",
				postal_code: item.address?.postal_code || "",
				email: item.address?.email || "",
				phone: item.address?.phone || "",
				contact: item.address?.contact || "",
				program: item.programs?.program || "",
				program_number: item.programs?.program_number || "",
				manufacturer_id: item.programs?.manufacturer_id || ""
			};
		} else {
			formData = {
				rfc: "",
				name: "",
				curp: "",
				type_nat_foreign: "N",
				client_or_provider: "client",
				is_active: true,
				streets: "",
				exterior_number: "",
				interior_number: "",
				neighborhood: "",
				municipality: "",
				city: "",
				state: "",
				country: "",
				postal_code: "",
				email: "",
				phone: "",
				contact: "",
				program: "",
				program_number: "",
				manufacturer_id: ""
			};
		}
	});

	const isEditing = $derived(!!item);
	const isForeign = $derived((formData.type_nat_foreign || "N").toUpperCase() === "E");

	// Validación de formato: RFC (Nacional) o TAX-ID (Extranjero)
	const RFC_REGEX = /^[A-Z&Ñ]{3,4}\d{6}[A-Z0-9]{3}$/i;
	// TAX-ID: 2 dígitos, guión, resto alfanumérico. Ej: 12-3456789. Máx 30 caracteres.
	const TAX_ID_REGEX = /^\d{2}-[A-Z0-9]{1,27}$/i;

	async function handleSubmit(e: Event) {
		e.preventDefault();
		
		if (!companyStore.activeCompany) {
			error = "No hay compañía seleccionada";
			return;
		}

		const rfcVal = (formData.rfc || "").trim();
		if (isForeign) {
			if (!TAX_ID_REGEX.test(rfcVal)) {
				error = "El TAX-ID debe tener formato: 2 dígitos, guión y resto (ej. 12-3456789). Máx 30 caracteres.";
				return;
			}
		} else {
			if (!RFC_REGEX.test(rfcVal)) {
				error = "El RFC no tiene el formato correcto. Ejemplo: XAXX010101000.";
				return;
			}
		}

		loading = true;
		error = null;

		try {
			let response;
			if (isEditing && item) {
				const payload: UpdateClientProviderData = {
					rfc: formData.rfc,
					name: formData.name,
					curp: formData.curp || null,
					client_or_provider: formData.client_or_provider as "client" | "provider" | "both" | null,
					type_nat_foreign: (formData.type_nat_foreign || null) as any,
					is_active: formData.is_active,
					address: {
						streets: formData.streets || null,
						exterior_number: formData.exterior_number || null,
						interior_number: formData.interior_number || null,
						neighborhood: formData.neighborhood || null,
						municipality: formData.municipality || null,
						city: formData.city || null,
						state: formData.state || null,
						country: formData.country || null,
						postal_code: formData.postal_code || null,
						email: formData.email || null,
						phone: formData.phone || null,
						contact: formData.contact || null,
					},
					programs: {
						program: formData.program || null,
						program_number: formData.program_number || null,
						manufacturer_id: formData.manufacturer_id || null,
					}
				};
				response = await clientsProvidersApi.update(item.id, companyStore.activeCompany.id, payload);
			} else {
				const payload: CreateClientProviderData = {
					rfc: formData.rfc,
					name: formData.name,
					curp: formData.curp || null,
					client_or_provider: formData.client_or_provider as "client" | "provider" | "both" | null,
					type_nat_foreign: (formData.type_nat_foreign || null) as any,
					is_active: formData.is_active,					
					address: {
						streets: formData.streets || null,
						exterior_number: formData.exterior_number || null,
						interior_number: formData.interior_number || null,
						neighborhood: formData.neighborhood || null,
						municipality: formData.municipality || null,
						city: formData.city || null,
						state: formData.state || null,
						country: formData.country || null,
						postal_code: formData.postal_code || null,
						email: formData.email || null,
						phone: formData.phone || null,
						contact: formData.contact || null,
					},
					programs: {
						program: formData.program || null,
						program_number: formData.program_number || null,
						manufacturer_id: formData.manufacturer_id || null,                        
					}
				};
				response = await clientsProvidersApi.create(companyStore.activeCompany.id, payload);
			}

			if (response.error) {
				if (response.status === 401) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 1500);
				} else {
					error = response.error;
				}
				return;
			}

			// Éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : "Error al guardar";
			console.error("Error saving:", e);
		} finally {
			loading = false;
		}
	}

	function handleOpenChange(newOpen: boolean) {
		if (!newOpen) {
			// Limpiar form al cerrar
			formData = {
				rfc: "",
				name: "",
				curp: "",
				type_nat_foreign: "N",
				client_or_provider: "client",
				is_active: true,
				streets: "",
				exterior_number: "",
				interior_number: "",
				neighborhood: "",
				municipality: "",
				city: "",
				state: "",
				country: "",
				postal_code: "",
				email: "",
				phone: "",
				contact: "",
				program: "",
				program_number: "",
				manufacturer_id: ""
			};
			error = null;
		}
		open = newOpen;
	}
</script>

<Dialog.Root bind:open onOpenChange={handleOpenChange}>
	<Dialog.Content class="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>
				{isEditing ? "Editar" : "Nuevo"} Cliente/Proveedor
			</Dialog.Title>
			<Dialog.Description>
				{isEditing 
					? "Modifica los datos del cliente o proveedor."
					: "Completa los datos para crear un nuevo cliente o proveedor."}
			</Dialog.Description>
		</Dialog.Header>

		<form onsubmit={handleSubmit} class="space-y-6">
			{#if error}
				<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<!-- Información básica -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Información Básica</h3>
				
				<div class="grid grid-cols-3 gap-4">
					<div class="space-y-2">
						<Label for="type_nat_foreign">Procedencia *</Label>
						<select
							id="type_nat_foreign"
							bind:value={formData.type_nat_foreign}
							required
							disabled={loading}
							class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
						>
							<option value="N">Nacional</option>
							<option value="E">Extranjero</option>
						</select>
					</div>
					<div class="space-y-2">
						<Label for="rfc">{isForeign ? "TAX-ID" : "RFC"} *</Label>
						<Input
							id="rfc"
							bind:value={formData.rfc}
							placeholder={isForeign ? "Ej: 12-3456789 (según país)" : "Ej: XAXX010101000"}
							maxlength={30}
							required
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="client_or_provider">Tipo *</Label>
						<select
							id="client_or_provider"
							bind:value={formData.client_or_provider}
							required
							disabled={loading}
							class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
						>
							<option value="client">Cliente</option>
							<option value="provider">Proveedor</option>
							<option value="both">Ambos</option>
						</select>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="name">Nombre / Razón Social *</Label>
					<Input
						id="name"
						bind:value={formData.name}
						placeholder="Nombre completo o razón social"
						maxlength={256}
						required
						disabled={loading}
					/>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="curp">CURP</Label>
						<Input
							id="curp"
							bind:value={formData.curp}
							placeholder="Ej: XAXX010101HDFXXX00"
							maxlength={18}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="residence_country">País de Residencia</Label>
						<Input
							id="residence_country"
							bind:value={formData.residence_country}
							placeholder="Ej: México"
							maxlength={64}
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<!-- Dirección -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Dirección</h3>
				
				<div class="space-y-2">
					<Label for="streets">Calles</Label>
					<Input
						id="streets"
						bind:value={formData.streets}
						placeholder="Calle y referencias"
						maxlength={256}
						disabled={loading}
					/>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="exterior_number">Número exterior</Label>
						<Input
							id="exterior_number"
							bind:value={formData.exterior_number}
							placeholder="Ej: 123"
							maxlength={20}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="interior_number">Número interior</Label>
						<Input
							id="interior_number"
							bind:value={formData.interior_number}
							placeholder="Ej: 4B"
							maxlength={20}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="neighborhood">Colonia</Label>
						<Input
							id="neighborhood"
							bind:value={formData.neighborhood}
							placeholder="Colonia o barrio"
							maxlength={128}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="postal_code">Código Postal</Label>
						<Input
							id="postal_code"
							bind:value={formData.postal_code}
							placeholder="Ej: 12345"
							maxlength={10}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="municipality">Municipio</Label>
						<Input
							id="municipality"
							bind:value={formData.municipality}
							placeholder="Municipio"
							maxlength={150}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="city">Ciudad</Label>
						<Input
							id="city"
							bind:value={formData.city}
							placeholder="Ciudad"
							maxlength={128}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="state">Estado</Label>
						<Input
							id="state"
							bind:value={formData.state}
							placeholder="Estado o provincia"
							maxlength={128}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="country">País</Label>
					<Input
						id="country"
						bind:value={formData.country}
						placeholder="País"
						maxlength={64}
						disabled={loading}
					/>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="email">Email</Label>
						<Input
							id="email"
							bind:value={formData.email}
							placeholder="correo@dominio.com"
							maxlength={100}
							disabled={loading}
						/>
					</div>
					<div class="space-y-2">
						<Label for="phone">Teléfono</Label>
						<Input
							id="phone"
							bind:value={formData.phone}
							placeholder="Teléfono"
							maxlength={30}
							disabled={loading}
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="contact">Contacto</Label>
					<Input
						id="contact"
						bind:value={formData.contact}
						placeholder="Persona de contacto"
						maxlength={50}
						disabled={loading}
					/>
				</div>
			</div>

			<!-- Programas -->
			<div class="space-y-4">
				<h3 class="text-sm font-semibold">Programas</h3>
				
				<div class="grid grid-cols-3 gap-4">
					<div class="space-y-2">
						<Label for="program">Programa</Label>
						<Input
							id="program"
							bind:value={formData.program}
							placeholder="Ej: IMMEX"
							maxlength={7}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="program_number">Número de Programa</Label>
						<Input
							id="program_number"
							bind:value={formData.program_number}
							placeholder="Número"
							maxlength={40}
							disabled={loading}
						/>
					</div>

					<div class="space-y-2">
						<Label for="manufacturer_id">Manufacturer ID</Label>
						<Input
							id="manufacturer_id"
							bind:value={formData.manufacturer_id}
							placeholder="Manufacturer ID"
							maxlength={25}
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<Dialog.Footer>
				<Button
					type="button"
					variant="outline"
					onclick={() => (open = false)}
					disabled={loading}
				>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					{isEditing ? "Guardar cambios" : "Crear"}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
