<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 { createIdentifier, updateIdentifier, type Identifier } from "$lib/api/dashboard/a76/identifiers";
    import { companyStore } from "$lib/stores/company.svelte";

	let {
		open = $bindable(false),
		mode = 'create',
		item = null,
		onSuccess
	}: {
		open: boolean;
		mode?: 'create' | 'edit';
		item?: Identifier | null;
		onSuccess?: () => void;
	} = $props();

	const isEdit = $derived(mode === 'edit');
	const title = $derived(isEdit ? "Editar Identificador" : "Nuevo Identificador");

	let formData = $state({
		code: '',
		description: '',
        level: '',
        complement: ''
	});

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

	$effect(() => {
		if (open) {
			if (isEdit && item) {
				formData = {
					code: item.code,
					description: item.description || '',
                    level: item.level || '',
                    complement: item.complement || ''
				};
			} else {
				formData = {
					code: '',
					description: '',
                    level: '',
                    complement: ''
				};
			}
			error = null;
		}
	});

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

		loading = true;
		error = null;

		try {
			let response;
			if (isEdit && item) {
				response = await updateIdentifier(item.id, {
					code: formData.code,
					description: formData.description || null,
                    level: formData.level || null,
                    complement: formData.complement || null
				});
			} else {
				response = await createIdentifier({
					code: formData.code,
					description: formData.description || null,
                    level: formData.level || null,
                    complement: formData.complement || null,
                    company_id: companyId
				});
			}

			if (response.error) {
				error = response.error;
				return;
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = 'Error de conexión';
			console.error(e);
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>
		
		<div class="grid gap-4 py-4">
			{#if error}
				<div class="text-red-500 text-sm mb-2">{error}</div>
			{/if}
			
			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="code" class="text-right">Clave</Label>
				<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
			</div>
			
			<div class="grid grid-cols-4 items-center gap-4">
				<Label for="description" class="text-right">Descripción</Label>
				<Textarea id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
			</div>

            <div class="grid grid-cols-4 items-center gap-4">
				<Label for="level" class="text-right">Nivel</Label>
				<Input id="level" bind:value={formData.level} class="col-span-3" disabled={loading} />
			</div>

            <div class="grid grid-cols-4 items-center gap-4">
				<Label for="complement" class="text-right">Complemento</Label>
				<Textarea id="complement" bind:value={formData.complement} class="col-span-3" disabled={loading} />
			</div>
		</div>

		<Dialog.Footer>
			<Button type="submit" onclick={handleSubmit} disabled={loading}>
				{loading ? 'Guardando...' : 'Guardar'}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
