"use client";

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

export type AttributesOverview = z.infer<typeof AttributeDTOSchema>;

interface AttributeActionsCellProps {
  attribute: AttributesOverview;
  handleRowClick: (attribute: AttributesOverview) => void;
  router: any;
  startTransition: (scope: () => void) => void;
}

const AttributeActionsCell = ({
  attribute,
  handleRowClick,
  router,
  startTransition,
}: AttributeActionsCellProps) => {
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const { execute: executeDelete, isLoading: isDeleting } = useAction(deleteAttribute);

  const onDelete = async () => {
    const result = await executeDelete({ id: attribute.id });
    if (result?.success) {
      toast.success("Attribut erfolgreich gelöscht.");
      setShowDeleteDialog(false);
      startTransition(() => {
        router.refresh();
      });
    } else if (result?.error) {
      toast.error(result.error);
    }
  };

  const onEdit = (e: React.MouseEvent) => {
    e.stopPropagation();
    handleRowClick(attribute);
  };

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0" disabled={isDeleting}>
            <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>
          <DropdownMenuItem
            onSelect={(e) => {
              e.preventDefault();
              setShowDeleteDialog(true);
            }}
            className="text-destructive focus:text-destructive"
          >
            <Trash className="mr-2 h-4 w-4" />
            Löschen
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent onClick={(e) => e.stopPropagation()}>
          <AlertDialogHeader>
            <AlertDialogTitle>Attribut löschen</AlertDialogTitle>
            <AlertDialogDescription>
              Möchten Sie das Attribut &quot;{attribute.name}&quot; wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Abbrechen</AlertDialogCancel>
            <AlertDialogAction
              onClick={(e) => {
                e.preventDefault();
                onDelete();
              }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={isDeleting}
            >
              {isDeleting ? "Löscht..." : "Löschen"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export const getColumns = (
  handleRowClick: (attribute: AttributesOverview) => void,
  router: any,
  startTransition: (scope: () => void) => void
): ColumnDef<AttributesOverview>[] => [
  {
    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;
      if (!date) return "-";
      return formatDate(date);
    },
  },
  {
    id: "actions",
    cell: ({ row }) => (
      <AttributeActionsCell
        attribute={row.original}
        handleRowClick={handleRowClick}
        router={router}
        startTransition={startTransition}
      />
    ),
  },
];
