<script lang="ts">
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Button } from '$lib/components/ui/button';
	import { Folder } from 'lucide-svelte';
    import type { Item, LineDescriptions } from '$lib/api/dashboard/a76/items';
	import type { InvoiceItemVisibility } from '$lib/config/invoice-item-visibility';
	import PaymentMethodDialog from './payment-method-dialog.svelte';
	import LocationSelectorDialog from './location-selector-dialog.svelte';
	import { m } from '$lib/i18n/messages';

    let {
        lineItem = $bindable(),
		descriptions = $bindable(),
		visibility,
		disabled = false
    }: {
        lineItem: Partial<Item>;
        descriptions: LineDescriptions;
		visibility: InvoiceItemVisibility;
		disabled?: boolean;
    } = $props();


    let taxPaidValue = $derived(lineItem.tax_payment ? 'si' : 'no');
    function setTaxPaid(val: string) {
        lineItem.tax_payment = val === 'si';
    }

    let hasCertificateValue = $derived(lineItem.has_certificate ? 'si' : 'no');
    function setHasCertificate(val: string) {
        lineItem.has_certificate = val === 'si';
    }

	// Initialize boolean fields to prevent bind:checked={undefined} error
	if (lineItem.is_military_mcia === undefined) {
		lineItem.is_military_mcia = false;
	}
	if (lineItem.has_fda_code === undefined) {
		lineItem.has_fda_code = false;
	}
	if (descriptions.consider_a31 === undefined) {
		descriptions.consider_a31 = false;
	}
	if (!lineItem.fa_data) {
		lineItem.fa_data = {};
	}
	if (lineItem.fa_data.own_equipment === undefined) {
		lineItem.fa_data.own_equipment = false;
	}
	if (lineItem.fa_data.omit_annex31 === undefined) {
		lineItem.fa_data.omit_annex31 = false;
	}

	let paymentMethodDialogOpen = $state(false);
	let payment_method_description = $state('');
	let locationSelectorOpen = $state(false);

	// Load payment method description when payment_method exists
	$effect(() => {
		async function loadPaymentMethodData() {
			// Si ya tiene la descripción cargada por enrichItemData, usarla
			if ((lineItem as any).payment_method_description) {
				payment_method_description = (lineItem as any).payment_method_description;
				return;
			}

			// Si tiene payment_method pero no descripción, cargarla
			if (lineItem.payment_method && !payment_method_description) {
				try {
					const response = await fetch('/api-sveltekit/payment-methods', {
						credentials: 'include'
					});
					if (response.ok) {
						const data = await response.json();
						const methods = data.items || data.data || data;
						if (Array.isArray(methods)) {
							const method = methods.find((m: any) => m.key === lineItem.payment_method);
							if (method) {
								payment_method_description = method.description;
							}
						}
					}
				} catch (error) {
					console.error('Error loading payment method data:', error);
				}
			}
		}
		loadPaymentMethodData();
	});

	function handlePaymentMethodSelect(method: any) {
		lineItem.payment_method = method.key;
		payment_method_description = method.description;
	}

	function handleLocationSelect(loc: { clave_localizacion: string; localizacion?: string | null }) {
		descriptions.machinery_location = loc.localizacion ?? loc.clave_localizacion ?? '';
	}
</script>

<div class="grid grid-cols-1 items-start gap-2 lg:grid-cols-2">
	<!-- Left Column -->
	<div class="space-y-2">
		{#if visibility.showContinuationTaxPayment}
		<!-- TAX PAID -->
		<div class="grid grid-cols-4 gap-2">
			<fieldset class="border rounded p-1.5 space-y-1">
				<legend class="text-xs font-semibold px-1.5 bg-gray-200 dark:bg-gray-700">{m['invoice_item_fa.continuation.tax_paid']()}</legend>
				<RadioGroup.Root 
                    value={taxPaidValue} 
                    onValueChange={setTaxPaid}
                    disabled={disabled}
                    class="flex gap-2">

					<div class="flex items-center space-x-1.5">
						<RadioGroup.Item value="si" id="pago_impuesto_si" />
						<Label for="pago_impuesto_si" class="text-xs font-normal">{m['invoice_item_fa.continuation.yes']()}</Label>
					</div>
					<div class="flex items-center space-x-1.5">
						<RadioGroup.Item value="no" id="pago_impuesto_no" />
						<Label for="pago_impuesto_no" class="text-xs font-normal">No</Label>
					</div>
				</RadioGroup.Root>								
			</fieldset>
			<div class="space-y-0.5">
				<div class="space-y-0.5">
					<Label for="forma_pago" class="text-xs">{m['invoice_item_fa.continuation.payment_method']()}:</Label>
					<div class="flex gap-1">
						<Input id="forma_pago" bind:value={lineItem.payment_method} disabled={disabled} class="h-6 text-xs flex-1" />
						<Button 
							size="icon" 
							variant="outline" 
							class="h-6 w-6 shrink-0"
							disabled={disabled}
							onclick={() => !disabled && (paymentMethodDialogOpen = true)}
							type="button"
						>
							<Folder class="h-3 w-3" />
						</Button>
					</div>

				</div>
				<Label for="credito_iva" class="text-xs">{payment_method_description || ''}</Label>								
			</div>
		</div>
		{/if}

		{#if visibility.showContinuationIgi}
		<!-- IGI Amount -->
		<div class="grid grid-cols-2 gap-2">							
			<div class="space-y-0.5">
				<Label for="monto_igi" class="text-xs">{m['invoice_item_fa.continuation.igi_amount']()}:  {lineItem.igi_amount || 0} <span class="text-xs">{m['invoice_item_fa.continuation.dollars']()}</span></Label>							
                <Input id="monto_igi" type="number" bind:value={lineItem.igi_amount} disabled={disabled} class="h-6 text-xs" />
			</div>
			<div class="space-y-0.5">
				<Label for="igi_payment_method" class="text-xs">{m['invoice_item_fa.continuation.igi_payment_method']()}:</Label>
				<Input id="igi_payment_method" bind:value={lineItem.igi_payment_method} disabled={disabled} class="h-6 text-xs" />
			</div>

		</div>
		{/if}

		{#if visibility.showFdaFcc}
			<div class="space-y-2 rounded-md border p-2">
				<div class="text-xs font-semibold">FDA / FCC</div>
				<div class="grid grid-cols-1 gap-2 lg:grid-cols-3">
					<div class="flex items-center space-x-1.5">
						<Checkbox id="has_fda_code" bind:checked={lineItem.has_fda_code} disabled={disabled} />
						<Label for="has_fda_code" class="text-xs font-normal">{m['invoice_item_fa.continuation.has_fda_code']()}</Label>
					</div>
					<div class="space-y-0.5">
						<Label for="fda_key" class="text-xs">Clave FDA:</Label>
						<Input id="fda_key" bind:value={lineItem.fda_key} disabled={disabled} class="h-6 text-xs" maxlength={20} />
					</div>
					<div class="space-y-0.5">
						<Label for="fcc_key" class="text-xs">Clave FCC:</Label>
						<Input id="fcc_key" bind:value={lineItem.fcc_key} disabled={disabled} class="h-6 text-xs" maxlength={30} />
					</div>

				</div>
			</div>
		{/if}
		
		{#if visibility.showCertificateOfOrigin}
			<!-- Certificate of Origin -->
			<div class="grid grid-cols-4 gap-2">
				<fieldset class="border rounded p-1.5 space-y-1">
					<legend class="text-xs font-semibold px-1.5 bg-gray-200 dark:bg-gray-700">{m['invoice_item_fa.continuation.has_certificate_of_origin']()}</legend>
					<RadioGroup.Root 
                    value={hasCertificateValue} 
                    onValueChange={setHasCertificate}
                    disabled={disabled}
                    class="flex gap-2">

						<div class="flex items-center space-x-1.5">
							<RadioGroup.Item value="si" id="cert_origen_si" />
							<Label for="cert_origen_si" class="text-xs font-normal">{m['invoice_item_fa.continuation.yes']()}</Label>
						</div>
						<div class="flex items-center space-x-1.5">
							<RadioGroup.Item value="no" id="cert_origen_no" />
							<Label for="cert_origen_no" class="text-xs font-normal">No</Label>
						</div>
					</RadioGroup.Root>
				</fieldset>
				<div class="col-span-3 space-y-0.5">
					<Label for="num_cert_origen" class="text-xs">{m['invoice_item_fa.continuation.certificate_number']()}:</Label>
					<Input id="num_cert_origen" bind:value={lineItem.certificate_number} class="h-6 text-xs" disabled={disabled || !lineItem.has_certificate} />
					<Label for="cert_end_date" class="text-xs">{m['invoice_item_fa.continuation.end_date']()}:</Label>
					<Input id="cert_end_date" type="text" bind:value={lineItem.certificate_end_date} class="h-6 text-xs" placeholder="YYYY-MM-DD" disabled={disabled || !lineItem.has_certificate} />
				</div>

			</div>
		{/if}

		{#if visibility.showExportValuationFields || visibility.showValuationFields}
			<!-- Valoración: Met Valor, Valor Det., Motivo De Uso (expo or import CR per legacy). -->
			<div class="space-y-2 rounded-md border p-2">
				<div class="text-xs font-semibold">Valoración</div>
				<div class="grid grid-cols-1 gap-2 lg:grid-cols-3">
					<div class="space-y-0.5">
						<Label for="met_valor" class="text-xs">Met Valor:</Label>
						<Input id="met_valor" bind:value={lineItem.valuation_method} disabled={disabled} class="h-6 text-xs" maxlength={2} placeholder="Método" />
					</div>
					<div class="space-y-0.5">
						<Label for="valor_det" class="text-xs">Valor Det.:</Label>
						<Input id="valor_det" type="number" step="0.00000001" bind:value={lineItem.valuation_determined_value} disabled={disabled} class="h-6 text-xs" />
					</div>
					<div class="space-y-0.5 lg:col-span-1">
						<Label for="motivo_uso" class="text-xs">Motivo De Uso:</Label>
						<textarea
							id="motivo_uso"
							bind:value={lineItem.valuation_reason}
							disabled={disabled}
							class="min-h-[60px] w-full rounded-md border border-input bg-background px-2 py-1 text-xs ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
							placeholder="Razón valoración"
							maxlength={500}
						></textarea>
					</div>

				</div>
			</div>
		{/if}

		{#if visibility.showContinuationLocation}
		<!-- Location (catálogo a76, sistema fixed_asset) -->
		<div class="space-y-1">
			<div class="space-y-0.5">
				<Label for="localizacion_maquinaria" class="text-xs">{m['invoice_item_fa.continuation.machinery_equipment_location']()}:</Label>
				<div class="flex gap-1">
					<button
						id="localizacion_maquinaria"
						type="button"
						disabled={disabled}
						onclick={() => !disabled && (locationSelectorOpen = true)}
						class="flex h-6 min-w-[120px] flex-1 items-center rounded-md border border-input bg-transparent px-2 text-left text-xs ring-offset-background disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
					>
						{descriptions.machinery_location || 'Seleccionar ubicación...'}
					</button>

				</div>
				<Label for="localizacion_maquinaria" class="text-xs text-muted-foreground">{m['invoice_item_fa.continuation.location_variable']()}</Label>
			</div>
			<LocationSelectorDialog
				bind:open={locationSelectorOpen}
				system="fixed_asset"
				onSelect={handleLocationSelect}
			/>
		</div>
		{/if}

		{#if visibility.showContinuationMilitary}
		<!-- Military Equipment -->
		<div class="flex items-center space-x-1.5 ">
			<Checkbox id="equipo_militar" bind:checked={lineItem.is_military_mcia} disabled={disabled} />
			<Label for="equipo_militar" class="text-xs font-normal">{m['invoice_item_fa.continuation.military_equipment_enable']()}</Label>
		</div>

		{/if}

		{#if visibility.showContinuationOwnOmitAnnex && lineItem.fa_data}
		<div class="grid grid-cols-1 gap-2 lg:grid-cols-2">
			<div class="flex items-center space-x-1.5 ">
				<Checkbox id="fa_own_equipment" bind:checked={lineItem.fa_data.own_equipment} disabled={disabled} />
				<Label for="fa_own_equipment" class="text-xs font-normal">{m['invoice_item_fa.continuation.own_equipment']()}</Label>
			</div>
			<div class="flex items-center space-x-1.5 ">
				<Checkbox id="fa_omit_annex31" bind:checked={lineItem.fa_data.omit_annex31} disabled={disabled} />
				<Label for="fa_omit_annex31" class="text-xs font-normal">{m['invoice_item_fa.continuation.omit_annex31']()}</Label>
			</div>

		</div>
		{/if}

		{#if visibility.showContinuationLotEntry}
		<!-- Lot and Entry Number -->
		<div class="grid grid-cols-2 gap-2">
			<div class="space-y-0.5">
				<Label for="lote" class="text-xs">{m['invoice_item_fa.continuation.lot']()}:</Label>
				<Input id="lote" bind:value={descriptions.lot} disabled={disabled} class="h-6 text-xs" />
			</div>
			<div class="space-y-0.5">
				<Label for="num_entrada" class="text-xs">{m['invoice_item_fa.continuation.entry_number']()}:</Label>
				<Input id="num_entrada" bind:value={descriptions.entry_number} disabled={disabled} class="h-6 text-xs" />
			</div>

		</div>
		{/if}
	</div>

	<!-- Right Column -->
	<div class="flex h-full flex-col gap-2">
		{#if visibility.showEighthRule}
			<!-- Permit and Eighth Rule Fraction -->
			<div class="space-y-1">
				<div class="space-y-0.5">
					<Label for="permiso_regla_octava" class="text-xs">{m['invoice_item_fa.continuation.eighth_rule_permit']()}:</Label>
					<div class="flex gap-1">
						<Input id="permiso_regla_octava" bind:value={lineItem.octave_permit} disabled={disabled} class="h-6 text-xs" />
					</div>
				</div>
				<div class="grid grid-cols-4 items-end gap-2">
					<div class="col-span-3 space-y-0.5">
						<Label for="fraccion_regla_octava" class="text-xs">{m['invoice_item_fa.continuation.eighth_rule_fraction']()}:</Label>
						<Input id="fraccion_regla_octava" bind:value={descriptions.eighth_rule_fraction} disabled={disabled} class="h-6 text-xs" />
					</div>
					<div class="space-y-0.5">
						<Label for="linea_regla" class="text-xs">{m['invoice_item_fa.continuation.line']()}:</Label>
						<Input id="linea_regla" type="number" min="0" bind:value={descriptions.eighth_rule_line} disabled={disabled} class="h-6 text-xs text-right" />
					</div>
				</div>

			</div>
		{/if}

		{#if visibility.showContinuationConsiderA31}
		<!-- Consider in a31 -->
		<div class="flex items-center space-x-1.5 ">
			<Checkbox id="a31" bind:checked={descriptions.consider_a31} disabled={disabled} />
			<Label for="a31" class="text-xs font-normal">{m['invoice_item_fa.continuation.consider_a31']()}</Label>
		</div>

		{/if}

		{#if visibility.showContinuationExtraDescription}
		<!-- Extra Description -->
		<div class="flex-1 space-y-0.5">
			<Label for="desc_extra_espanol" class="text-xs">{m['invoice_item_fa.continuation.extra_description_spanish']()}:</Label>
			<textarea 
				id="desc_extra_espanol"
				bind:value={descriptions.extra_description}
				disabled={disabled}
				class="flex min-h-[60px] w-full flex-1 rounded-md border border-input bg-background px-2 py-1 text-xs ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
			></textarea>
		</div>

		{/if}
	</div>
</div>
<PaymentMethodDialog bind:open={paymentMethodDialogOpen} onSelect={handlePaymentMethodSelect} />