<script lang="ts">
	import Loader from "$lib/components/atoms/loader.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import * as AlertDialog from "$lib/components/ui/alert-dialog/index";
	import { Badge } from "$lib/components/ui/badge";
	import Button from "$lib/components/ui/button/button.svelte";
	import * as Dialog from "$lib/components/ui/dialog";
	import { productVM } from "$lib/domains/product/product.vm.svelte";
	import { Copy, Pencil, PlusIcon, RefreshCw, Trash2 } from "@lucide/svelte";
	import { onMount } from "svelte";
	import type { CreateProductPayload } from "../data";
	import ProductForm from "./product-form.svelte";

	let createDialogOpen = $state(false);
	let editDialogOpen = $state(false);
	let deleteDialogOpen = $state(false);

	let newProductData = $state<CreateProductPayload>(
		productVM.getDefaultProduct(),
	);

	async function handleCreateProduct() {
		const success = await productVM.createProduct(newProductData);
		if (success) {
			createDialogOpen = false;
			newProductData = productVM.getDefaultProduct();
		}
	}

	async function handleUpdateProduct() {
		if (!productVM.selectedProduct) return;

		const success = await productVM.updateProduct({
			id: productVM.selectedProduct.id! ?? -1,
			...productVM.selectedProduct,
		});
		if (success) {
			editDialogOpen = false;
		}
	}

	async function handleDeleteProduct() {
		if (!productVM.selectedProduct) return;

		const success = await productVM.deleteProduct(
			productVM.selectedProduct.id!,
		);
		if (success) {
			deleteDialogOpen = false;
		}
	}

	async function handleRefreshLinkId(id: number) {
		await productVM.refreshProductLinkId(id);
	}

	async function handleCopyLink(linkId: string) {
		await productVM.copyLinkToClipboard(linkId);
	}

	function formatPrice(price: number) {
		return `$${price.toFixed(2)}`;
	}

	onMount(() => {
		setTimeout(async () => {
			productVM.fetchProducts();
		}, 1000);
	});
</script>

<div class="mb-6 flex items-center justify-between">
	<Title size="h3" weight="semibold">Products</Title>
	<Button onclick={() => (createDialogOpen = true)}>
		<PlusIcon class="mr-2 h-4 w-4" />
		New Product
	</Button>
</div>

{#if productVM.loading}
	<div class="flex items-center justify-center py-20">
		<Loader />
	</div>
{:else if productVM.products.length === 0}
	<div class="rounded-lg border py-10 text-center">
		<p class="text-gray-500">
			No products found. Create your first product to get started.
		</p>
	</div>
{:else}
	<div class="overflow-x-auto">
		<table class="w-full divide-y divide-gray-200">
			<thead class="bg-gray-50">
				<tr>
					<th
						class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
						>Product</th
					>
					<th
						class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
						>Pricing</th
					>
					<th
						class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
						>Link ID</th
					>
					<th
						class="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500"
						>Actions</th
					>
				</tr>
			</thead>
			<tbody class="divide-y divide-gray-200 bg-white">
				{#each productVM.products as product}
					<tr>
						<td class="whitespace-nowrap px-6 py-4">
							<div class="font-medium text-gray-900">
								{product.title}
							</div>
							<div
								class="max-w-48 overflow-hidden text-ellipsis text-sm text-gray-500"
							>
								{product.description}
							</div>
						</td>

						<td class="whitespace-nowrap px-6 py-4">
							<div class="flex flex-col gap-1">
								<div class="text-sm">
									<span class="text-gray-500">Price:</span>
									<span class="ml-1 font-medium"
										>{formatPrice(product.price)}</span
									>
								</div>
								{#if product.discountPrice > 0 && product.discountPrice < product.price}
									<Badge variant="success" class="w-fit">
										Discount: {formatPrice(
											product.discountPrice,
										)}
									</Badge>
								{/if}
							</div>
						</td>

						<td class="px-6 py-4">
							<div class="flex items-center gap-2">
								<code
									class="rounded bg-gray-100 px-2 py-1 font-mono text-xs"
								>
									{product.linkId}
								</code>
								<Button
									variant="ghost"
									size="sm"
									onclick={() => handleCopyLink(product.linkId)}
								>
									<Copy class="h-3 w-3" />
								</Button>
							</div>
						</td>

						<td
							class="flex w-full items-center justify-end gap-2 whitespace-nowrap px-6 py-4 text-right"
						>
							<Button
								variant="ghost"
								size="sm"
								onclick={() => handleRefreshLinkId(product.id!)}
								title="Refresh Link ID"
							>
								<RefreshCw class="h-4 w-4" />
							</Button>

							<Button
								variant="ghost"
								size="sm"
								onclick={() => {
									productVM.selectProduct(product);
									editDialogOpen = true;
								}}
							>
								<Pencil class="h-4 w-4" />
							</Button>

							<Button
								variant="ghost"
								size="sm"
								onclick={() => {
									productVM.selectProduct(product);
									deleteDialogOpen = true;
								}}
							>
								<Trash2 class="h-4 w-4" />
							</Button>
						</td>
					</tr>
				{/each}
			</tbody>
		</table>
	</div>
{/if}

<!-- Create Product Dialog -->
<Dialog.Root bind:open={createDialogOpen}>
	<Dialog.Content class="max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>Create New Product</Dialog.Title>
			<Dialog.Description>
				Create a new product for your catalog.
			</Dialog.Description>
		</Dialog.Header>

		<ProductForm
			formData={newProductData}
			loading={productVM.formLoading}
			onSubmit={handleCreateProduct}
			onCancel={() => (createDialogOpen = false)}
		/>
	</Dialog.Content>
</Dialog.Root>

<!-- Edit Product Dialog -->
<Dialog.Root bind:open={editDialogOpen}>
	<Dialog.Content class="max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>Edit Product</Dialog.Title>
			<Dialog.Description>Update this product's details.</Dialog.Description
			>
		</Dialog.Header>

		{#if productVM.selectedProduct}
			<ProductForm
				formData={productVM.selectedProduct}
				loading={productVM.formLoading}
				onSubmit={handleUpdateProduct}
				onCancel={() => (editDialogOpen = false)}
			/>
		{/if}
	</Dialog.Content>
</Dialog.Root>

<!-- Delete Confirmation Dialog -->
<AlertDialog.Root bind:open={deleteDialogOpen}>
	<AlertDialog.Content>
		<AlertDialog.Header>
			<AlertDialog.Title>Delete Product</AlertDialog.Title>
			<AlertDialog.Description>
				Are you sure you want to delete this product? This action cannot
				be undone.
			</AlertDialog.Description>
		</AlertDialog.Header>

		{#if productVM.selectedProduct}
			<div class="mb-4 rounded-md bg-gray-100 p-4">
				<div class="font-bold">{productVM.selectedProduct.title}</div>
				<div class="text-sm text-gray-600">
					{productVM.selectedProduct.description}
				</div>
				<div class="mt-2 flex items-center gap-2">
					<Badge
						>Price: {formatPrice(
							productVM.selectedProduct.price,
						)}</Badge
					>
					{#if productVM.selectedProduct.discountPrice > 0}
						<Badge variant="success"
							>Discount: {formatPrice(
								productVM.selectedProduct.discountPrice,
							)}</Badge
						>
					{/if}
				</div>
			</div>
		{/if}

		<AlertDialog.Footer>
			<AlertDialog.Cancel onclick={() => (deleteDialogOpen = false)}>
				Cancel
			</AlertDialog.Cancel>
			<AlertDialog.Action
				onclick={handleDeleteProduct}
				disabled={productVM.formLoading}
			>
				{productVM.formLoading ? "Deleting..." : "Delete"}
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>
