<script lang="ts">
	import * as Drawer from "$lib/components/ui/drawer/index.js";
	import {
		BikeIcon,
		CarIcon,
		PlusCircleIcon,
		TractorIcon,
		TruckIcon,
		XIcon,
	} from "@lucide/svelte";
	import Button, { buttonVariants } from "../ui/button/button.svelte";
	import {
		DefaultVehicle,
		selectedVehicle,
		selectVehicle,
		vehicles,
		type VehicleType,
	} from "$lib/vehicles/vehicles.svelte";
	import AddVehicleDrawer from "./AddVehicleDrawer.svelte";
	import { m } from "$lang/messages";
	import { updateStore } from "$lib/services/stores.svelte";

	let open = $state(false);

	function getVehicleIcon(type: VehicleType) {
		switch (type) {
			case "car":
				return CarIcon;
			case "motor_scooter":
				return TractorIcon;
			case "bicycle":
				return BikeIcon;
			case "motorcycle":
				return BikeIcon;
			case "truck":
				return TruckIcon;
			default:
				return TractorIcon; // Default icon if no match
		}
	}
</script>

<Drawer.Root bind:open>
	<Drawer.Trigger
		class={buttonVariants({ variant: "secondary", class: "w-full p-5" })}
	>
		{@const vehicle = selectedVehicle() ?? DefaultVehicle}
		{@const Icon = getVehicleIcon(vehicle.type)}
		<Icon />
		{vehicle.name}
	</Drawer.Trigger>
	<Drawer.Content>
		<Drawer.Header>
			<Drawer.Title>{m["vehicles.selector.title"]()}</Drawer.Title>
			<Drawer.Description
				>{m["vehicles.selector.description"]()}</Drawer.Description
			>
		</Drawer.Header>
		<div class="p-4 pt-0 flex flex-col gap-2">
			{#each vehicles.current as vehicle (vehicle.name)}
				<div class="flex items-center gap-2">
					<Button
						variant={selectedVehicle() === vehicle.data ? "default" : "secondary"}
						class="w-[calc(100%-48px-8px)] p-5"
						onclick={() => {
							selectVehicle(vehicle.data);
							open = false;
						}}
					>
						{@const Icon = getVehicleIcon(vehicle.data.type)}
						<Icon />
						{vehicle.data.name}
					</Button>
					<Button variant="destructive" class="w-[48px]" onclick={() => {
						if(!confirm("Are you sure you want to delete this vehicle? This action cannot be undone.")) return;
						updateStore({ type: "vehicle", name: vehicle.name }, null);
					}}>
						<XIcon />
					</Button>
				</div>
			{/each}

			<AddVehicleDrawer>
				<Button variant="secondary" class="w-full p-5">
					<PlusCircleIcon />
					{m["vehicles.selector.add"]()}
				</Button>
			</AddVehicleDrawer>
		</div>
	</Drawer.Content>
</Drawer.Root>
