<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 Tabs from '$lib/components/ui/tabs';
	import { Switch } from '$lib/components/ui/switch';
	import {
		createConcept,
		updateConcept,
		type Concept
	} from '$lib/api/dashboard/a76/general_catalogs/concepts';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioConceptos } from '$lib/config/shortcuts/dashboard/general_catalogs/concepts/edit';

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

	// Atajos

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

	let formData = $state({
		code: '',
		description: '',
		description_en: '',
		detailed_description: '',
		priority: '',
		priority_ame: '',
		first_total: '',
		type: '',
		is_printed: false,
		section: '',
		classification: ''
	});

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

	function resetForm() {
		formData = {
			code: '',
			description: '',
			description_en: '',
			detailed_description: '',
			priority: '',
			priority_ame: '',
			first_total: '',
			type: '',
			is_printed: false,
			section: '',
			classification: ''
		};
	}

	// Cargar/limpiar datos al abrir
	$effect(() => {
		if (!open) return;

		if (item) {
			formData = {
				code: item.code || '',
				description: item.description || '',
				description_en: item.description_en || '',
				detailed_description: item.detailed_description || '',
				priority: item.priority ? String(item.priority) : '', // Asegurar string
				priority_ame: item.priority_ame ? String(item.priority_ame) : '',
				first_total: item.first_total ? String(item.first_total) : '',
				type: item.type || '',
				is_printed: item.is_printed || false,
				section: item.section || '',
				classification: item.classification || ''
			};
		} else {
			resetForm();
		}

		error = null;
	});

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

		if (!companyStore.activeCompany) {
			error = 'No hay una empresa seleccionada. Recarga la página.';
			loading = false;
			return;
		}
		const companyId = companyStore.activeCompany.id;

		try {
			if (!formData.code.trim()) throw new Error('El código es requerido');

			const dataToSend = {
				code: formData.code.trim(),
				company_id: companyId,
				description: formData.description.trim(),
				description_en: formData.description_en.trim() || null,
				detailed_description: formData.detailed_description.trim() || null,
				priority: formData.priority ? parseInt(formData.priority) : null,
				priority_ame: formData.priority_ame ? parseInt(formData.priority_ame) : null,
				section: formData.section ? parseInt(formData.section) : null,
				first_total: !!formData.first_total,
				type: formData.type.trim() || null,
				is_printed: Boolean(formData.is_printed),
				classification: formData.classification.trim() || null
			};

			let response;

			if (isEdit && item) {
				response = await updateConcept(item.id, dataToSend, companyId);
			} else {
				response = await createConcept(dataToSend, companyId);
			}

			if (response.error) {
				throw new Error(response.error); // Axios a veces devuelve error en el body
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar';
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-2xl max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="space-y-4"
		>
			{#if error}
				<div class="p-3 text-sm text-red-600 bg-red-50 rounded-md border border-red-200">
					{error}
				</div>
			{/if}

			<Tabs.Root value="general" class="w-full">
				<Tabs.Content value="general" class="space-y-4 py-4">
					<div class="grid gap-2">
						<Label for="code">Código <span class="text-destructive">*</span></Label>
						<Input id="code" bind:value={formData.code} maxlength={10} />
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="priority">Prioridad</Label>
							<Input id="priority" bind:value={formData.priority} type="number" />
						</div>
						<div class="grid gap-2">
							<Label for="priority_ame">Prioridad AME</Label>
							<Input id="priority_ame" bind:value={formData.priority_ame} type="number" />
						</div>
					</div>

					<div class="grid gap-2">
						<Label for="description">Descripción <span class="text-destructive">*</span></Label>
						<Input id="description" bind:value={formData.description} maxlength={100} />
					</div>

					<div class="grid gap-2">
						<Label for="description_en">Descripción (Inglés)</Label>
						<Input id="description_en" bind:value={formData.description_en} maxlength={100} />
					</div>

					<div class="grid gap-2">
						<Label for="detailed_description">Descripción Detallada</Label>
						<Input id="detailed_description" bind:value={formData.detailed_description} />
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="first_total">Primer Total</Label>
							<Input id="first_total" bind:value={formData.first_total} type="number" />
						</div>
						<div class="grid gap-2">
							<Label for="type">Tipo</Label>
							<Input id="type" bind:value={formData.type} maxlength={5} />
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="grid gap-2">
							<Label for="section">Sección</Label>
							<Input id="section" bind:value={formData.section} maxlength={10} />
						</div>
						<div class="grid gap-2">
							<Label for="classification">Clasificación</Label>
							<Input id="classification" bind:value={formData.classification} maxlength={10} />
						</div>
					</div>

					<div class="flex items-center space-x-2 pt-2">
						<Switch id="is_printed" bind:checked={formData.is_printed} />
						<Label for="is_printed">¿Se Imprime?</Label>
					</div>
				</Tabs.Content>
			</Tabs.Root>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)}>Cancelar</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : 'Guardar Concepto'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
