"use client";

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

export type CustomersOverview = z.infer<typeof CustomerDTOSchema>;

function CustomerActionsCell({ customer }: { customer: CustomersOverview }) {
  const router = useRouter();
  const { execute, isLoading } = useAction(deleteCustomer);

  const handleDelete = async () => {
    const result = await execute({ id: customer.id });
    if (result?.success) {
      toast.success("Kunde 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">
        <DropdownMenuLabel>Aktionen</DropdownMenuLabel>
        <DropdownMenuItem asChild>
          <Link href={`/dashboard/customers/edit/${customer.id}`}>
            <Edit className="mr-2 h-4 w-4" />
            Bearbeiten
          </Link>
        </DropdownMenuItem>
        <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>Kunden löschen</AlertDialogTitle>
              <AlertDialogDescription>
                Möchten Sie den Kunden &quot;{customer.name}&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>
  );
}

export const columns: ColumnDef<CustomersOverview>[] = [
  {
    accessorKey: "id",
    header: "ID",
    cell: ({ row }) => (
      <span className="text-xs text-muted-foreground font-mono">
        #{row.getValue("id")}
      </span>
    ),
  },
  {
    accessorKey: "name",
    header: "Name",
  },
  {
    accessorKey: "email",
    header: "Email",
  },
  {
    accessorKey: "phone_number",
    header: "Telefonnummer",
  },
  {
    accessorKey: "created_at",
    header: "Erstellt am",
    cell: ({ row }) => {
      return formatDate(row.getValue("created_at") as string);
    },
  },
  {
    id: "actions",
    cell: ({ row }) => <CustomerActionsCell customer={row.original} />,
  },
];
