"use client";

import { ColumnDef } from "@tanstack/react-table";
import { BrandDTOSchema } from "@/lib/db/schemas/api";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Trash2, Pencil, MoreHorizontal } from "lucide-react";
import { deleteBrand } from "@/actions/catalog";
import { toast } from "sonner";
import { formatDate } from "@/lib/format";
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 { useAction } from "@/hooks/useAction";
import { useRouter } from "next/navigation";

export type BrandsOverview = z.infer<typeof BrandDTOSchema>;

export const getColumns = (
  handleRowClick: (brand: BrandsOverview) => void,
  _router: any
): ColumnDef<BrandsOverview>[] => [
  {
    accessorKey: "id",
    header: "ID",
    cell: ({ row }) => (
      <span className="text-xs text-muted-foreground font-mono">
        #{row.getValue("id") || "Neu"}
      </span>
    ),
  },
  { accessorKey: "name", header: "Name" },
  {
    accessorKey: "createdAt",
    header: "Erstellt am",
    cell: ({ row }) => {
      const date = row.getValue("createdAt") as Date | null;
      return date ? formatDate(date) : "-";
    },
  },
  {
    id: "actions",
    cell: ({ row }) => <BrandActionsCell brand={row.original} onEdit={(e) => {
      e.stopPropagation();
      handleRowClick(row.original);
    }} />,
  },
];

function BrandActionsCell({ brand, onEdit }: { brand: BrandsOverview; onEdit: (e: React.MouseEvent) => void }) {
  const router = useRouter();
  const { execute, isLoading } = useAction(deleteBrand);

  const handleDelete = async () => {
    const result = await execute({ id: brand.id });
    if (result?.success) {
      toast.success("Marke 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} onClick={(e) => e.stopPropagation()}>
          <span className="sr-only">Menü öffnen</span>
          <MoreHorizontal className="h-4 w-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
        <DropdownMenuLabel>Aktionen</DropdownMenuLabel>
        <DropdownMenuItem onClick={onEdit}><Pencil className="mr-2 h-4 w-4" />Bearbeiten</DropdownMenuItem>
        <DropdownMenuSeparator />
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <DropdownMenuItem onSelect={(e) => e.preventDefault()} className="text-destructive">
              <Trash2 className="mr-2 h-4 w-4" />Löschen
            </DropdownMenuItem>
          </AlertDialogTrigger>
          <AlertDialogContent onClick={(e) => e.stopPropagation()}>
            <AlertDialogHeader>
              <AlertDialogTitle>Marke löschen</AlertDialogTitle>
              <AlertDialogDescription>Möchten Sie die Marke &quot;{brand.name}&quot; wirklich löschen?</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>
  );
}
