<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 PaymentMethodDialog from './payment-method-dialog.svelte';

    let {
        lineItem = $bindable(),
        descriptions = $bindable()
    }: {
        lineItem: Partial<Item>;
        descriptions: LineDescriptions;
    } = $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 (descriptions.consider_a31 === undefined) {
		descriptions.consider_a31 = false;
	}

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

	// 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;
	}
</script>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-2">
	<!-- Left Column -->
	<div class="space-y-2">
		<!-- 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">TAX PAID</legend>
				<RadioGroup.Root 
                    value={taxPaidValue} 
                    onValueChange={setTaxPaid}
                    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">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">Payment Method:</Label>
					<div class="flex gap-1">
						<Input id="forma_pago" bind:value={lineItem.payment_method} class="h-6 text-xs flex-1" />
						<Button 
							size="icon" 
							variant="outline" 
							class="h-6 w-6 shrink-0"
							onclick={() => 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>

		<!-- IGI Amount -->
		<div class="grid grid-cols-2 gap-2">							
			<div class="space-y-0.5">
				<Label for="monto_igi" class="text-xs">IGI Amount:  {lineItem.igi_amount || 0} <span class="text-xs">DOLLARS</span></Label>								
                <Input id="monto_igi" type="number" bind:value={lineItem.igi_amount} class="h-6 text-xs" />
			</div>
		</div>
		
		<!-- 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">Has Certificate of Origin?</legend>
				<RadioGroup.Root 
                    value={hasCertificateValue} 
                    onValueChange={setHasCertificate}
                    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">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="space-y-0.5 col-span-3">
				<Label for="num_cert_origen" class="text-xs">Certificate of Origin No.:</Label>
				<Input id="num_cert_origen" bind:value={lineItem.certificate_number} class="h-6 text-xs" />
				<Label for="num_cert_origen" class="text-xs">End Date:</Label>
			</div>
		</div>

		<!-- Location -->
		<div class="space-y-1">						
			<div class="space-y-0.5">
				<Label for="localizacion_maquinaria" class="text-xs">Machinery and equipment location:</Label>
				<div class="flex gap-1">
					<Input id="localizacion_maquinaria" bind:value={descriptions.machinery_location} class="h-6 text-xs" />									
				</div>
				<Label for="localizacion_maquinaria" class="text-xs">Location variable</Label>
			</div>
		</div>

		<!-- Military Equipment -->
		<div class="flex items-center space-x-1.5 ">
			<Checkbox id="equipo_militar" bind:checked={lineItem.is_military_mcia} />
			<Label for="equipo_militar" class="text-xs font-normal">Enable if Item Contains Military Equipment</Label>
		</div>

		<!-- Lot and Entry Number -->
		<div class="grid grid-cols-2 gap-2">
			<div class="space-y-0.5">
				<Label for="lote" class="text-xs">Lot:</Label>
				<Input id="lote" bind:value={descriptions.lot} class="h-6 text-xs" />
			</div>
			<div class="space-y-0.5">
				<Label for="num_entrada" class="text-xs">Entry No.:</Label>
				<Input id="num_entrada" bind:value={descriptions.entry_number} class="h-6 text-xs" />
			</div>
		</div>						
	</div>

	<!-- Right Column -->
	<div class="space-y-2">					
		<!-- Permit and Eighth Rule Fraction -->
		<div class="space-y-1">
			<div class="space-y-0.5">
				<Label for="permiso_regla_octava" class="text-xs">Eighth Rule Permit:</Label>
				<div class="flex gap-1">
					<Input id="permiso_regla_octava" bind:value={lineItem.octave_permit} class="h-6 text-xs" />								
				</div>
			</div>
			<div class="grid grid-cols-4 gap-2 items-end">
				<div class="space-y-0.5 col-span-3">
					<Label for="fraccion_regla_octava" class="text-xs">Eighth Rule Fraction:</Label>
					<Input id="fraccion_regla_octava" bind:value={descriptions.eighth_rule_fraction} class="h-6 text-xs" />
				</div>
				<div class="space-y-0.5">
					<Label for="linea_regla" class="text-xs">Line:</Label>
					<Input id="linea_regla" type="number" min="0" bind:value={descriptions.eighth_rule_line} class="h-6 text-xs text-right" />
				</div>
			</div>
		</div>				
		
		<!-- Consider in a31 -->
		<div class="flex items-center space-x-1.5 ">
			<Checkbox id="a31" bind:checked={descriptions.consider_a31} />
			<Label for="a31" class="text-xs font-normal">Consider in A31</Label>
		</div>

		<!-- Extra Description -->
		<div class="space-y-0.5">
			<Label for="desc_extra_espanol" class="text-xs">Extra Description in Spanish:</Label>
			<textarea 
				id="desc_extra_espanol"
				bind:value={descriptions.description_spanish}
				class="flex min-h-[60px] w-full 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>																		
	</div>
</div>
<PaymentMethodDialog bind:open={paymentMethodDialogOpen} onSelect={handlePaymentMethodSelect} />