<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 { Textarea } from "$lib/components/ui/textarea";
	import * as Select from "$lib/components/ui/select";
	import { classesApi, type A76Class, type A76ClassCreate, type A76ClassUpdate } from "$lib/api/dashboard/a76/classes";
	import { materialTypesApi, type MaterialType } from "$lib/api/dashboard/refrence_data/material_types";
	import { companyStore } from "$lib/stores/company.svelte";
	import { onMount } from 'svelte';

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

	// Determinar si es modo edición o creación
	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? "Editar Clase" : "Nueva Clase");

	// Estado del formulario
	let formData = $state({
		class_code: item?.class_code || '',
		description_es: item?.description_es || '',
		description_en: item?.description_en || '',
		material_key: item?.material_key || '',
		unit_of_measure: item?.unit_of_measure || 'KG',
		fraction: item?.fraction || '',
		us_fraction: item?.us_fraction || '',
		sub_key: item?.sub_key || '',
		physical_review: item?.physical_review || 0,
		iva_exempt_fraction: item?.iva_exempt_fraction || ''
	});

	let loading = $state(false);
	let error = $state<string | null>(null);
	let materialTypes = $state<MaterialType[]>([]);
	let loadingMaterialTypes = $state(false);
	
	// Variables para controlar los selects
	let selectedUnitValue = $state<string>('KG');
	let selectedMaterialValue = $state<string>('');
	let selectedPhysicalReviewValue = $state<number>(0);

	// Cargar tipos de materiales al montar
	onMount(async () => {
		loadingMaterialTypes = true;
		try {
			const response = await materialTypesApi.list(1, 100); // Cargar los primeros 100
			if (response.data) {
				materialTypes = response.data.items;
			}
		} catch (e) {
			console.error('Error loading material types:', e);
		} finally {
			loadingMaterialTypes = false;
		}
	});

	// Resetear formulario cuando cambia el item
	$effect(() => {
		if (item) {
			formData = {
				class_code: item.class_code,
				description_es: item.description_es || '',
				description_en: item.description_en || '',
				material_key: item.material_key || '',
				unit_of_measure: item.unit_of_measure,
				fraction: item.fraction,
				us_fraction: item.us_fraction,
				sub_key: item.sub_key,
				physical_review: item.physical_review,
				iva_exempt_fraction: item.iva_exempt_fraction
			};
			// Actualizar valores de los selects
			selectedUnitValue = item.unit_of_measure;
			selectedMaterialValue = item.material_key || '';
			selectedPhysicalReviewValue = item.physical_review;
		} else {
			// Reset para modo crear
			formData = {
				class_code: '',
				description_es: '',
				description_en: '',
				material_key: '',
				unit_of_measure: 'KG',
				fraction: '',
				us_fraction: '',
				sub_key: '',
				physical_review: 0,
				iva_exempt_fraction: ''
			};
			// Resetear valores de los selects
			selectedUnitValue = 'KG';
			selectedMaterialValue = '';
			selectedPhysicalReviewValue = 0;
		}
		error = null;
	});

	function handleOpenChange(newOpen: boolean) {
		open = newOpen;
		if (!newOpen) {
			error = null;
		}
	}

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

		// Validaciones básicas
		if (!formData.class_code.trim()) {
			error = 'El código de clase es requerido';
			return;
		}
		if (!formData.fraction.trim()) {
			error = 'La fracción es requerida';
			return;
		}
		if (!formData.us_fraction.trim()) {
			error = 'La fracción US es requerida';
			return;
		}
		if (!formData.sub_key.trim()) {
			error = 'La subclave es requerida';
			return;
		}
		if (!formData.iva_exempt_fraction.trim()) {
			error = 'La fracción exenta de IVA es requerida';
			return;
		}

		loading = true;
		error = null;

		try {
			let response;

			if (isEdit && item) {
				// Actualizar
				const updateData: A76ClassUpdate = {
					class_code: formData.class_code,
					description_es: formData.description_es || null,
					description_en: formData.description_en || null,
					material_key: formData.material_key || null,
					unit_of_measure: formData.unit_of_measure,
					fraction: formData.fraction,
					us_fraction: formData.us_fraction,
					sub_key: formData.sub_key,
					physical_review: formData.physical_review,
					iva_exempt_fraction: formData.iva_exempt_fraction
				};
				response = await classesApi.update(item.id, updateData, companyId);
			} else {
				// Crear - usa el company_id como client_id
				const createData: A76ClassCreate = {
					company_id: companyId,
					client_id: companyId, // Usa el mismo company_id como client_id
					class_code: formData.class_code,
					description_es: formData.description_es || null,
					description_en: formData.description_en || null,
					material_key: formData.material_key || null,
					unit_of_measure: formData.unit_of_measure,
					fraction: formData.fraction,
					us_fraction: formData.us_fraction,
					sub_key: formData.sub_key,
					physical_review: formData.physical_review,
					iva_exempt_fraction: formData.iva_exempt_fraction
				};
				response = await classesApi.create(createData, companyId);
			}

			if (response.error) {
				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 class:', e);
		} finally {
			loading = false;
		}
	}

	// Opciones de unidades de medida (puedes expandir esto)
	const unitOptions = [
		{ value: 'KG', label: 'Kilogramos (KG)' },
		{ value: 'LB', label: 'Libras (LB)' },
		{ value: 'MT', label: 'Metros (MT)' },
		{ value: 'PZ', label: 'Piezas (PZ)' },
		{ value: 'LT', label: 'Litros (LT)' },
		{ value: 'M3', label: 'Metros Cúbicos (M3)' },
		{ value: 'TON', label: 'Toneladas (TON)' }
	];

	// Funciones para obtener valores seleccionados
	function getSelectedMaterialType() {
		if (!formData.material_key) return null;
		const found = materialTypes.find(mt => mt.key === formData.material_key);
		return found ? { value: found.key, label: `${found.key} - ${found.description}` } : null;
	}

	function getSelectedUnit() {
		return unitOptions.find(opt => opt.value === formData.unit_of_measure) || unitOptions[0];
	}

	function getSelectedPhysicalReview() {
		return { value: formData.physical_review, label: formData.physical_review === 1 ? 'Sí' : 'No' };
	}
</script>

<Dialog.Root bind:open onOpenChange={handleOpenChange}>
	<Dialog.Content class="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit ? 'Modifica los datos de la clase' : 'Completa los datos para crear una nueva clase'}
			</Dialog.Description>
		</Dialog.Header>

		<form onsubmit={handleSubmit} class="space-y-4 py-4">
			<!-- Error Message -->
			{#if error}
				<div class="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<!-- Información de la compañía (solo lectura) -->
			{#if companyStore.activeCompany}
				<div class="rounded-md bg-blue-50 border border-blue-200 p-3">
					<div class="flex items-center gap-2">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							width="16"
							height="16"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							stroke-linecap="round"
							stroke-linejoin="round"
							class="text-blue-600"
						>
							<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
							<polyline points="9 22 9 12 15 12 15 22" />
						</svg>
						<div>
							<p class="text-sm font-medium text-blue-900">
								{companyStore.activeCompany.name}
							</p>
							<p class="text-xs text-blue-600">
								ID: {companyStore.activeCompany.id}
							</p>
						</div>
					</div>
				</div>
			{/if}

			<!-- Código de Clase -->
			<div class="space-y-2">
				<Label for="class_code" class="required">Código de Clase</Label>
				<Input
					id="class_code"
					bind:value={formData.class_code}
					placeholder="Ej: A76"
					required
					disabled={loading}
				/>
			</div>

			<!-- Descripciones -->
			<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="description_es">Descripción (Español)</Label>
					<Textarea
						id="description_es"
						bind:value={formData.description_es}
						placeholder="Descripción en español"
						disabled={loading}
						rows={3}
					/>
				</div>

				<div class="space-y-2">
					<Label for="description_en">Descripción (Inglés)</Label>
					<Textarea
						id="description_en"
						bind:value={formData.description_en}
						placeholder="English description"
						disabled={loading}
						rows={3}
					/>
				</div>
			</div>

			<!-- Material Type -->
			<div class="space-y-2">
				<Label for="material_key">Tipo de Material</Label>
				{#if loadingMaterialTypes}
					<div class="flex items-center gap-2 text-sm text-muted-foreground">
						<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
						Cargando tipos de material...
					</div>
				{:else if materialTypes.length > 0}
					<select 
						bind:value={formData.material_key}
						disabled={loading}
						class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
					>
						<option value="">Sin tipo de material</option>
						{#each materialTypes as materialType}
							<option value={materialType.key}>
								{materialType.key} - {materialType.description}
							</option>
						{/each}
					</select>
				{:else}
					<Input
						id="material_key"
						bind:value={formData.material_key}
						placeholder="No hay tipos de material disponibles"
						disabled={true}
					/>
				{/if}
			</div>

			<!-- Fracciones -->
			<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="fraction" class="required">Fracción</Label>
					<Input
						id="fraction"
						bind:value={formData.fraction}
						placeholder="Ej: 123123"
						required
						disabled={loading}
					/>
				</div>

				<div class="space-y-2">
					<Label for="us_fraction" class="required">Fracción US</Label>
					<Input
						id="us_fraction"
						bind:value={formData.us_fraction}
						placeholder="Ej: 123123"
						required
						disabled={loading}
					/>
				</div>
			</div>

			<!-- Sub Key e IVA Exempt -->
			<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="sub_key" class="required">Subclave</Label>
					<Input
						id="sub_key"
						bind:value={formData.sub_key}
						placeholder="Ej: 123"
						required
						disabled={loading}
					/>
				</div>

				<div class="space-y-2">
					<Label for="iva_exempt_fraction" class="required">Fracción Exenta IVA</Label>
					<Input
						id="iva_exempt_fraction"
						bind:value={formData.iva_exempt_fraction}
						placeholder="Ej: 123"
						required
						disabled={loading}
					/>
				</div>
			</div>

			<!-- Unidad de Medida -->
			<div class="space-y-2">
				<Label for="unit_of_measure" class="required">Unidad de Medida</Label>
				<select 
					bind:value={formData.unit_of_measure}
					disabled={loading}
					class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
				>
					{#each unitOptions as unit}
						<option value={unit.value}>{unit.label}</option>
					{/each}
				</select>
			</div>

			<!-- Revisión Física -->
			<div class="space-y-2">
				<Label for="physical_review">Revisión Física</Label>
				<select 
					bind:value={formData.physical_review}
					disabled={loading}
					class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
				>
					<option value={0}>No</option>
					<option value={1}>Sí</option>
				</select>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{#if loading}
						<svg
							class="mr-2 h-4 w-4 animate-spin"
							xmlns="http://www.w3.org/2000/svg"
							fill="none"
							viewBox="0 0 24 24"
						>
							<circle
								class="opacity-25"
								cx="12"
								cy="12"
								r="10"
								stroke="currentColor"
								stroke-width="4"
							></circle>
							<path
								class="opacity-75"
								fill="currentColor"
								d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
							></path>
						</svg>
						Guardando...
					{:else}
						{isEdit ? 'Actualizar' : 'Crear'}
					{/if}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>

<style>
	:global(.required::after) {
		content: " *";
		color: hsl(var(--destructive));
	}
</style>
