"use client";

import { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { MoreHorizontal, Edit, Trash } from "lucide-react";
import Link from "next/link";
import { deleteProduct } from "@/actions/catalog";
import { toast } from "sonner";
import Image from "next/image";
import { formatCurrency } from "@/lib/format";
import { CopyButton } from "@/components/ui/CopyButton";
import { useAction } from "@/hooks/useAction";
import { useRouter } from "next/navigation";

export type ProductsOverview = {
  id: string;
  image?: string;
  title: string;
  price: number;
  inventory: number;
  sku: string;
  ean?: string;
};

export const columns: ColumnDef<ProductsOverview>[] = [
  {
    accessorKey: "image",
    header: "Bild",
    cell: ({ row }) => {
      return (
        <Image
          src={
            row.getValue("image") ||
            "https://vdxl.im/8720287346401_a_en_hd_1.jpg"
          }
          alt="Produktbild"
          width={50}
          height={50}
        />
      );
    },
  },
  {
    accessorKey: "title",
    header: "Name",
    cell: ({ row }) => {
      const title = row.getValue("title") as string;
      return (
        <div className="flex items-center gap-2">
          <Link href={`/product/${row.original.id}`} prefetch={false} className="hover:underline">
            {title}
          </Link>
          <CopyButton
            value={title}
            copyMessage="Name kopieren"
            successMessage="Name kopiert!"
            aria-label={`Produktname ${title} kopieren`}
            className="h-6 w-6 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"
          />
        </div>
      );
    },
  },
  {
    accessorKey: "price",
    header: "Preis",
    cell: ({ row }) => {
      return <div className="font-medium">{formatCurrency(row.getValue("price"))}</div>;
    },
  },
  {
    accessorKey: "inventory",
    header: "Lagerbestand",
    cell: ({ row }) => {
      const inventory = Number(row.getValue("inventory"));
      const stockPercentage = Math.min((inventory / 100) * 100, 100);
      let stockColor = "bg-green-500";

      if (inventory <= 10) {
        stockColor = "bg-red-500";
      } else if (inventory < 50) {
        stockColor = "bg-amber-500";
      }

      return (
        <div className="flex flex-col items-center gap-1 w-24">
          <div className="text-sm font-medium text-center">
            {inventory} auf Lager
          </div>
          <div
            className="relative w-full h-2 rounded-md bg-muted border overflow-hidden">
            <div
              className={`absolute top-0 left-0 h-full ${stockColor}`}
              style={{ width: `${stockPercentage}%` }}
            ></div>
          </div>
        </div>
      );
    },
  },
  {
    accessorKey: "sku",
    header: "Artikelnummer / SKU",
    cell: ({ row }) => {
      const sku = row.getValue("sku") as string;
      if (!sku) return "-";
      return (
        <div className="flex items-center gap-2 group/sku">
          <span className="font-mono text-xs">{sku}</span>
          <CopyButton
            value={sku}
            copyMessage="SKU kopieren"
            successMessage="SKU kopiert!"
            aria-label={`SKU ${sku} kopieren`}
            className="h-6 w-6 opacity-0 group-hover/sku:opacity-100 group-focus-within/sku:opacity-100 transition-opacity"
          />
        </div>
      );
    },
  },
  {
    accessorKey: "ean",
    header: "GTIN / EAN",
    cell: ({ row }) => {
      const ean = row.getValue("ean") as string;
      if (!ean) return "-";
      return (
        <div className="flex items-center gap-2 group/ean">
          <span className="font-mono text-xs">{ean}</span>
          <CopyButton
            value={ean}
            copyMessage="EAN kopieren"
            successMessage="EAN kopiert!"
            aria-label={`EAN ${ean} kopieren`}
            className="h-6 w-6 opacity-0 group-hover/ean:opacity-100 group-focus-within/ean:opacity-100 transition-opacity"
          />
        </div>
      );
    },
  },
  {
    id: "actions",
    cell: ({ row }) => <ProductActionsCell product={row.original} />,
  },
];

function ProductActionsCell({ product }: { product: ProductsOverview }) {
  const router = useRouter();
  const { execute, isLoading } = useAction(deleteProduct);

  const handleDelete = async () => {
    const result = await execute({ id: product.id });
    if (result?.success) {
      toast.success("Produkt erfolgreich gelöscht");
      router.refresh();
    } else if (result?.error) {
      toast.error(result.error);
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" className="h-8 w-8 p-0" disabled={isLoading}>
          <span className="sr-only">Menü öffnen</span>
          <MoreHorizontal className="h-4 w-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuLabel>Aktionen</DropdownMenuLabel>
        <DropdownMenuItem asChild>
          <Link href={`/dashboard/products/edit/${product.id}`}>
            <Edit className="mr-2 h-4 w-4" />
            Bearbeiten
          </Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <DropdownMenuItem
              onSelect={(e) => e.preventDefault()}
              className="text-destructive focus:text-destructive"
            >
              <Trash className="mr-2 h-4 w-4" />
              Löschen
            </DropdownMenuItem>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Produkt löschen</AlertDialogTitle>
              <AlertDialogDescription>
                Möchten Sie das Produkt &quot;{product.title}&quot; wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={isLoading}>Abbrechen</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDelete}
                disabled={isLoading}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {isLoading ? "Löscht..." : "Löschen"}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
