"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 } from "lucide-react";
import Link from "next/link";
import { OrderStatusBadge } from "@/components/dashboard/OrderStatusBadge";
import { FulfillmentStatusBadge } from "@/components/dashboard/FulfillmentStatusBadge";
import { PaymentStatusBadge } from "@/components/dashboard/PaymentStatusBadge";
import { CopyButton } from "@/components/ui/CopyButton";
import { formatCurrency, formatDateTime } from "@/lib/format";
import { deleteOrder } from "@/actions/orders";
import { useRouter } from "next/navigation";
import { useAction } from "@/hooks/useAction";
import { toast } from "sonner";

export type OrdersOverview = {
  id: string;
  amount_total: number;
  items_total: number;
  payment_status: string;
  order_status: string;
  fulfilment_status?: string;
  created_at: string | Date;
  last_updated_at: string | Date;
};

function ActionsCell({ order }: { order: OrdersOverview }) {
  const router = useRouter();
  const { execute, isLoading } = useAction(deleteOrder);

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

  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 onClick={() => router.push(`/dashboard/orders/edit/${order.id}`)}>
          Bearbeiten
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
              Löschen
            </DropdownMenuItem>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Bist du sicher?</AlertDialogTitle>
              <AlertDialogDescription>
                Diese Aktion kann nicht rückgängig gemacht werden. Dies wird die Bestellung dauerhaft löschen.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Abbrechen</AlertDialogCancel>
              <AlertDialogAction onClick={handleDelete} disabled={isLoading}>
                {isLoading ? "Löscht..." : "Löschen"}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

export const columns: ColumnDef<OrdersOverview>[] = [
  {
    accessorKey: "id",
    header: "ID",
    cell: ({ row }) => {
      const id = row.getValue("id") as string;
      return (
        <div className="flex items-center gap-2 group/id">
          <Link
            href={`/dashboard/orders/${id}`}
            prefetch={false}
            className="font-mono text-xs hover:underline"
          >
            {id}
          </Link>
          <CopyButton
            value={id}
            copyMessage="Bestell-ID kopieren"
            successMessage="ID kopiert!"
            aria-label={`Bestell-ID ${id} kopieren`}
            className="h-6 w-6 opacity-0 group-hover/id:opacity-100 group-focus-within/id:opacity-100 transition-opacity"
          />
        </div>
      );
    },
  },
  {
    accessorKey: "amount_total",
    header: () => <div>Gesamtbetrag</div>,
    cell: ({ row }) => {
      return <div className="font-medium">{formatCurrency(row.getValue("amount_total"))}</div>;
    },
  },
  {
    accessorKey: "items_total",
    header: () => <div>Artikelanzahl</div>,
    cell: ({ row }) => {
      const itemsRaw = row.getValue("items_total");
      const items = itemsRaw ? parseInt(String(itemsRaw), 10) : 0;
      return <div className="font-medium">{isNaN(items) ? 0 : items}</div>;
    },
  },
  {
    accessorKey: "payment_status",
    header: "Zahlungsstatus",
    cell: ({ row }) => {
      return <PaymentStatusBadge status={row.getValue("payment_status")} />;
    },
  },
  {
    accessorKey: "order_status",
    header: "Bestellstatus",
    cell: ({ row }) => {
      return <OrderStatusBadge status={row.getValue("order_status")} />;
    },
  },

  {
    accessorKey: "fulfilment_status",
    header: "Versandstatus",
    cell: ({ row }) => {
      return <FulfillmentStatusBadge status={row.getValue("fulfilment_status")} />;
    },
  },
  {
    accessorKey: "created_at",
    header: "Erstellt am",
    cell: ({ row }) => {
      return <div className="font-medium">{formatDateTime(row.getValue("created_at"))}</div>;
    },
  },
  {
    accessorKey: "last_updated_at",
    header: "Zuletzt aktualisiert",
    cell: ({ row }) => {
      return <div className="font-medium">{formatDateTime(row.getValue("last_updated_at"))}</div>;
    },
   },
   {
     id: "actions",
     header: "Aktionen",
     cell: ({ row }) => <ActionsCell order={row.original} />,
   },
 ];
