"use client";

import { ColumnDef } from "@tanstack/react-table";
import { ManufacturerDTOSchema } from "@/lib/db/schemas/api";
import { z } from "zod";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { MoreHorizontal, Edit, Trash } from "lucide-react";
import { deleteManufacturer } from "@/actions/catalog";
import { toast } from "sonner";
import { formatDate } from "@/lib/format";
import { useRouter } from "next/navigation";
import { useAction } from "@/hooks/useAction";

export type ManufacturersOverview = z.infer<typeof ManufacturerDTOSchema>;

export const getColumns = (
  handleRowClick: (manufacturer: ManufacturersOverview) => void
): ColumnDef<ManufacturersOverview>[] => [
  {
    accessorKey: "id",
    header: "ID",
  },
  {
    accessorKey: "companyName",
    header: "Firmenname",
  },
  {
    accessorKey: "email",
    header: "Email",
  },
  {
    accessorKey: "phoneNumber",
    header: "Telefonnummer",
  },
  {
    accessorKey: "createdAt",
    header: "Erstellt am",
    cell: ({ row }) => {
      const date = row.getValue("createdAt") as Date | string | null;
      if (!date) return "-";
      return formatDate(date);
    },
  },
  {
    id: "actions",
    cell: ({ row }) => (
      <ManufacturerActionsCell
        manufacturer={row.original}
        onEdit={() => handleRowClick(row.original)}
      />
    ),
  },
];

function ManufacturerActionsCell({
  manufacturer,
  onEdit,
}: {
  manufacturer: ManufacturersOverview;
  onEdit: () => void;
}) {
  const router = useRouter();
  const { execute, isLoading } = useAction(deleteManufacturer);

  const onDelete = async () => {
    const result = await execute({ id: manufacturer.id });
    if (result?.success) {
      toast.success("Hersteller erfolgreich gelöscht.");
      router.refresh();
    } else if (result?.error) {
      toast.error(result.error || "Fehler beim Löschen des Herstellers.");
    }
  };

  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">
        <DropdownMenuLabel>Aktionen</DropdownMenuLabel>
        <DropdownMenuItem onClick={onEdit}>
          <Edit className="mr-2 h-4 w-4" />
          Bearbeiten
        </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 onClick={(e) => e.stopPropagation()}>
            <AlertDialogHeader>
              <AlertDialogTitle>Hersteller löschen</AlertDialogTitle>
              <AlertDialogDescription>
                Möchten Sie den Hersteller &quot;{manufacturer.companyName}&quot; wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={isLoading}>Abbrechen</AlertDialogCancel>
              <AlertDialogAction
                onClick={onDelete}
                disabled={isLoading}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {isLoading ? "Löscht..." : "Löschen"}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
