<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 { Button } from '$lib/components/ui/button';
	import { Folder } from 'lucide-svelte';
	import PartNumberDialog from './part-number-dialog.svelte';
	import type { Item, LineDescriptions } from '$lib/api/dashboard/a76/items';
	import { m } from '$lib/i18n/messages';

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


	let showPartDialog = $state(false);

	// Initialize fa_data for fixed asset system
	if (!lineItem.fa_data) {
		lineItem.fa_data = {};
	}

	// Helper to map boolean to string for RadioGroup
	let isSubPartidaValue = $derived(lineItem.fa_data?.is_subitem ? 'subpartida' : 'partida');
	function setIsSubPartida(val: string) {
		if (!lineItem.fa_data) lineItem.fa_data = {};
		lineItem.fa_data.is_subitem = val === 'subpartida';
	}

	let containsSubPartidasValue = $derived(lineItem.fa_data?.contains_subitems ? 'si' : 'no');
	function setContinueSubPartidas(val: string) {
		if (!lineItem.fa_data) lineItem.fa_data = {};
		lineItem.fa_data.contains_subitems = val === 'si';
	}

	// Helper for subitem_number binding
	let subitemNumber = $derived.by(() => lineItem.fa_data?.subitem_number ?? 0);
	function setSubitemNumber(val: number) {
		if (!lineItem.fa_data) lineItem.fa_data = {};
		lineItem.fa_data.subitem_number = val;
	}

	function handlePartSelect(part: any) {
		lineItem.part_number_id = part.id;
		lineItem.part_number = part.part_number;
		// Store part number for display
		(lineItem as any).part_number_display = part.part_number;
		(lineItem as any).part_description_es = part.description_spanish;
		(lineItem as any).part_description_en = part.description_english;

		// Update actual values if descriptions container exists
		if (descriptions) {
			if (part.description_spanish) descriptions.description_spanish = part.description_spanish;
			if (part.description_english) descriptions.description_english = part.description_english;
		}

		if (!lineItem.fda_key && part.fda_key) {
			lineItem.fda_key = part.fda_key;
		}
		if (!lineItem.fcc_key && part.fcc_key) {
			lineItem.fcc_key = part.fcc_key;
		}
	}
</script>

<PartNumberDialog bind:open={showPartDialog} onSelect={handlePartSelect} />

<div class="space-y-3 lg:col-span-5">
	<!-- Is Item/Subitem and Contains Sub-Items -->
	<div class="grid grid-cols-2 gap-2">
		<fieldset class="space-y-2 rounded-md border p-2">
			<legend class="bg-zinc-200 px-2 text-xs font-semibold dark:bg-zinc-700">{m['invoice_item_fa.configuration.is']()}</legend>
			<RadioGroup.Root value={isSubPartidaValue} onValueChange={setIsSubPartida} disabled={disabled} class="flex gap-3">

				<div class="flex items-center space-x-2">
					<RadioGroup.Item value="partida" id="partida" />
					<Label for="partida" class="text-xs font-normal">{m['invoice_item_fa.configuration.item']()}</Label>
				</div>
				<div class="flex items-center space-x-2">
					<RadioGroup.Item value="subpartida" id="subpartida" />
					<Label for="subpartida" class="text-xs font-normal">{m['invoice_item_fa.configuration.subitem']()}</Label>
				</div>
			</RadioGroup.Root>
		</fieldset>
		{#if isSubPartidaValue === 'partida'}
			<fieldset class="space-y-2 rounded-md border p-2">
				<legend class="bg-zinc-200 px-2 text-xs font-semibold dark:bg-zinc-700"
					>{m['invoice_item_fa.configuration.contains_subitems']()}</legend
				>
				<RadioGroup.Root
					value={containsSubPartidasValue}
					onValueChange={setContinueSubPartidas}
					disabled={disabled}
					class="flex gap-3"
				>

					<div class="flex items-center space-x-2">
						<RadioGroup.Item value="si" id="continue_si" />
						<Label for="continue_si" class="text-xs font-normal">{m['invoice_item_fa.configuration.yes']()}</Label>
					</div>
					<div class="flex items-center space-x-2">
						<RadioGroup.Item value="no" id="continue_no" />
						<Label for="continue_no" class="text-xs font-normal">No</Label>
					</div>
				</RadioGroup.Root>
			</fieldset>
		{:else if isSubPartidaValue === 'subpartida'}
			<fieldset class="rounded-md border p-1">
				<legend class="bg-zinc-200 px-2 text-xs font-semibold dark:bg-zinc-700"
					>{m['invoice_item_fa.configuration.main_item_number']()}</legend
				>
			<Input
				id="subitem_number"
				type="number"
				value={subitemNumber}
				disabled={disabled}
				oninput={(e) => setSubitemNumber(e.currentTarget.valueAsNumber || 0)}
				class="h-7 text-xs"
				placeholder={m['invoice_item_fa.configuration.main_item_number_placeholder']()}
				data-item-validation-path="fa_data.subitem_number"
			/>
			</fieldset>
		{/if}
	</div>

	<!-- Descriptions -->
	<fieldset class="space-y-2 rounded-md border p-2">
		<div class="space-y-1">
			<Label for="num_parte" class="text-xs">Número de Parte:</Label>
			<div class="flex gap-1">
				<Input
					id="num_parte"
					type="text"
					value={(lineItem as any).part_number_display || ''}
					readonly
					disabled={disabled}
					class="h-7 flex-1 cursor-pointer bg-muted text-xs"
					placeholder="Selecciona número de parte"
					onclick={() => !disabled && (showPartDialog = true)}

				/>
				<Button
					variant="outline"
					size="icon"
					disabled={disabled}
					class="h-7 w-7 shrink-0"
					onclick={() => !disabled && (showPartDialog = true)}
				>

					<Folder class="h-3.5 w-3.5" />
				</Button>
			</div>
			{#if (lineItem as any).part_description_es}
				<p class="truncate text-xs text-muted-foreground">
					{(lineItem as any).part_description_es}
				</p>
			{/if}
		</div>

		<div class="space-y-1">
			<Label for="desc_espanol" class="text-xs"
				>{m['invoice_item_fa.configuration.description_spanish']()}: <span class="text-red-500">*</span></Label
			>
		<textarea
			id="desc_espanol"
			bind:value={descriptions.description_spanish}
			disabled={disabled}
			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:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
			data-item-validation-path="description.description_spanish"
		></textarea>

		</div>

		<div class="space-y-1">
			<Label for="desc_ingles" class="text-xs">{m['invoice_item_fa.configuration.description_english']()}: <span class="text-red-500">*</span></Label>
		<textarea
			id="desc_ingles"
			bind:value={descriptions.description_english}
			disabled={disabled}
			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:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
			data-item-validation-path="description.description_english"
		></textarea>

		</div>
	</fieldset>
</div>
