import type {  ColumnDef,  Row } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Ellipsis } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { incoterms } from "@/db/schema/procurementRFQ";
import { toast } from "sonner";
import { deleteIncoterm } from "../service";

type Incoterm = typeof incoterms.$inferSelect;

interface GetColumnsProps {
  setRowAction: (action: { type: string; row: Row<Incoterm> }) => void;
  onSuccess: () => void;
}

const handleDelete = async (code: string, onSuccess: () => void) => {
  const result = await deleteIncoterm(code);
  if (result.success) {
    toast.success("삭제 완료");
    onSuccess();
  } else {
    toast.error(result.error || "삭제 실패");
  }
};

export function getColumns({ setRowAction, onSuccess }: GetColumnsProps): ColumnDef<Incoterm>[] {
  return [
    {
      id: "code",
      header: () => <div>코드</div>,
      cell: ({ row }) => <div>{row.original.code}</div>,
      enableSorting: true,
      enableHiding: false,
    },
    {
      id: "description",
      header: () => <div>설명</div>,
      cell: ({ row }) => <div>{row.original.description}</div>,
      enableSorting: true,
      enableHiding: false,
    },
    {
      id: "isActive",
      header: () => <div>상태</div>,
      cell: ({ row }) => (
        <Badge variant={row.original.isActive ? "default" : "secondary"}>
          {row.original.isActive ? "활성" : "비활성"}
        </Badge>
      ),
      enableSorting: true,
      enableHiding: false,
    },
    {
      id: "createdAt",
      header: () => <div>생성일</div>,
      cell: ({ row }) => {
        const value = row.original.createdAt;
        const date = value ? new Date(value) : null;
        return date ? date.toLocaleDateString() : "";
      },
      enableSorting: true,
      enableHiding: false,
    },
    {
      id: "actions",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="Open menu"
              variant="ghost"
              className="flex size-8 p-0 data-[state=open]:bg-muted"
            >
              <Ellipsis className="size-4" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-40">
            <DropdownMenuItem
              onSelect={() => setRowAction({ type: "edit", row })}
            >
              수정
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={() => handleDelete(row.original.code, onSuccess)}
              className="text-destructive"
            >
              삭제
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];
} 