"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { Ellipsis } from "lucide-react"
import { toast } from "sonner"

import { getErrorMessage } from "@/lib/handle-error"
import { formatDate } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header"

import { VendorItem,  vendors } from "@/db/schema/vendors"
import { modifyVendor } from "../service"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { getRFQStatusIcon } from "@/lib/tasks/utils"
import { rfqHistoryColumnsConfig } from "@/config/rfqHistoryColumnsConfig"

export interface RfqHistoryRow {
  id: number;
  rfqCode: string | null;
  projectCode: string | null;
  projectName: string | null;
  description: string | null;
  dueDate: Date;
  status: "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED";
  vendorStatus: string;
  totalAmount: number | null;
  currency: string | null;
  leadTime: string | null;
  itemCount: number;
  tbeResult: string | null;
  cbeResult: string | null;
  createdAt: Date;
  items: {
    rfqId: number;
    id: number;
    itemCode: string;
    description: string | null;
    quantity: number | null;
    uom: string | null;
  }[];
}

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<RfqHistoryRow> | null>>;
  openItemsModal: (rfqId: number) => void;
}

/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction, openItemsModal }: GetColumnsProps): ColumnDef<RfqHistoryRow>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<RfqHistoryRow> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
        className="translate-y-0.5"
      />
    ),
    size: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<RfqHistoryRow> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      return (
        <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({ row, type: "update" })}
            >
              View Details
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 40,
  }

  // ----------------------------------------------------------------
  // 3) 일반 컬럼들
  // ----------------------------------------------------------------
  const basicColumns: ColumnDef<RfqHistoryRow>[] = rfqHistoryColumnsConfig.map((cfg) => {
    const column: ColumnDef<RfqHistoryRow> = {
      accessorKey: cfg.id,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      size: cfg.size,
    }

    if (cfg.id === "description") {
      column.cell = ({ row }) => {
        const description = row.original.description
        if (!description) return null
        return (
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="break-words whitespace-normal line-clamp-2">
                {description}
              </div>
            </TooltipTrigger>
            <TooltipContent side="bottom" className="max-w-[400px] whitespace-pre-wrap break-words">
              {description}
            </TooltipContent>
          </Tooltip>
        )
      }
    }

    if (cfg.id === "status") {
      column.cell = ({ row }) => {
        const statusVal = row.original.status
        if (!statusVal) return null
        const Icon = getRFQStatusIcon(statusVal)
        return (
          <div className="flex items-center">
            <Icon className="mr-2 size-4 text-muted-foreground" aria-hidden="true" />
            <span className="capitalize">{statusVal}</span>
          </div>
        )
      }
    }

    if (cfg.id === "totalAmount") {
      column.cell = ({ row }) => {
        const amount = row.original.totalAmount
        const currency = row.original.currency
        if (!amount || !currency) return null
        return (
          <div className="whitespace-nowrap">
            {`${currency} ${amount.toLocaleString()}`}
          </div>
        )
      }
    }

    if (cfg.id === "dueDate" || cfg.id === "createdAt") {
      column.cell = ({ row }) => (
        <div className="whitespace-nowrap">
          {formatDate(row.getValue(cfg.id), "KR")}
        </div>
      )
    }

    return column
  })

  const itemsColumn: ColumnDef<RfqHistoryRow> = {
    id: "items",
    header: "Items",
    cell: ({ row }) => {
      const rfq = row.original;
      const count = rfq.itemCount || 0;
      return (
        <Button variant="ghost" onClick={() => openItemsModal(rfq.id)}>
          {count === 0 ? "No Items" : `${count} Items`}
        </Button>
      )
    },
  }

  // ----------------------------------------------------------------
  // 4) 최종 컬럼 배열
  // ----------------------------------------------------------------
  return [
    selectColumn,
    ...basicColumns,
    itemsColumn,
    actionsColumn,
  ]
}