<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
	import { vehiclesApi, type Vehicle } from '$lib/api/dashboard/a76/vehicles';
	import { companyStore } from '$lib/stores/company.svelte';
	import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
	import CreateEditDialog from './create-edit-dialog.svelte';
	import { tv } from '$lib/i18n/vehicles';

	let {
		item,
		onSuccess,
		canEdit = true,
		canDelete = true
	}: {
		item: Vehicle;
		onSuccess?: () => void;
		canEdit?: boolean;
		canDelete?: boolean;
	} = $props();

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

	async function handleDelete() {
		if (
			!confirm(
				tv('delete_confirm', { key: item.vehicle_key })
			)
		) {
			return;
		}

		if (!companyStore.activeCompany) {
			alert(tv('no_company_error'));
			return;
		}

		loading = true;
		error = null;

		try {
			const response = await vehiclesApi.delete(item.vehicle_key, companyStore.activeCompany.id);

			if (response.error) {
				if (response.status === 401) {
					error = tv('session_expired');
					setTimeout(() => {
						window.location.reload();
					}, 1500);
				} else {
					error = response.error;
					alert(`${tv('delete_error_title')}\n\n${response.error}`);
				}
				return;
			}

			// Éxito
			alert(tv('delete_success_item', { key: item.vehicle_key }));
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : tv('delete_generic_error');
			alert(tv('delete_error_alert', { error }));
			console.error('Error deleting:', e);
		} finally {
			loading = false;
		}
	}

	function handleEdit() {
		selectedItem = item;
		dialogOpen = true;
	}

	function handleDialogSuccess() {
		dialogOpen = false;
		selectedItem = null;
		if (onSuccess) {
			onSuccess();
		}
	}
</script>

<DropdownMenu.Root>
	<DropdownMenu.Trigger>
		{#snippet child({ props })}
			<Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
				<span class="sr-only">{tv('menu_open')}</span>
				<EllipsisVertical size={16} />
			</Button>
		{/snippet}
	</DropdownMenu.Trigger>
	<DropdownMenu.Content align="end" class="w-[160px]">
		<DropdownMenu.Label>{tv('menu_actions')}</DropdownMenu.Label>
		<DropdownMenu.Separator />
		{#if canEdit}
			<DropdownMenu.Item onclick={handleEdit}>
				<Pencil size={16} class="mr-2" />
				{tv('edit')}
			</DropdownMenu.Item>
		{/if}
		{#if canDelete}
			<DropdownMenu.Separator />
			<DropdownMenu.Item onclick={handleDelete} class="text-destructive" disabled={loading}>
				{#if loading}
					<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
				{:else}
					<Trash2 size={16} class="mr-2" />
				{/if}
				{tv('delete')}
			</DropdownMenu.Item>
		{/if}
	</DropdownMenu.Content>
</DropdownMenu.Root>

<CreateEditDialog bind:open={dialogOpen} item={selectedItem} onSuccess={handleDialogSuccess} />
