// initial-rfq-detail-columns.tsx
"use client"

import * as React from "react"
import { type ColumnDef } from "@tanstack/react-table"
import { type Row } from "@tanstack/react-table"
import {
  Ellipsis, Building, Eye, Edit, Trash,
  MessageSquare, Settings, CheckCircle2, XCircle
} from "lucide-react"

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,
  DropdownMenuSeparator, DropdownMenuTrigger, DropdownMenuShortcut
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { InitialRfqDetailView } from "@/db/schema"


// RowAction 타입 정의
export interface DataTableRowAction<TData> {
  row: Row<TData>
  type: "update" | "delete"
}

interface GetInitialRfqDetailColumnsProps {
  onSelectDetail?: (detail: any) => void
  setRowAction?: React.Dispatch<React.SetStateAction<DataTableRowAction<InitialRfqDetailView> | null>>
}

export function getInitialRfqDetailColumns({
  onSelectDetail,
  setRowAction
}: GetInitialRfqDetailColumnsProps = {}): ColumnDef<InitialRfqDetailView>[] {

  return [
    /** ───────────── 체크박스 ───────────── */
    {
      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,
    },

    /** ───────────── RFQ 정보 ───────────── */
    {
      accessorKey: "initialRfqStatus",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="초기 RFQ 상태" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("initialRfqStatus") as string
        const getInitialStatusColor = (status: string) => {
          switch (status) {
            case "DRAFT": return "outline"
            case "Init. RFQ Sent": return "default"
            case "Init. RFQ Answered": return "success"
            case "S/L Decline": return "destructive"
            default: return "secondary"
          }
        }
        return (
          <Badge variant={getInitialStatusColor(status) as any}>
            {status}
          </Badge>
        )
      },
      size: 120
    },
    {
      accessorKey: "rfqCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 코드" />
      ),
      cell: ({ row }) => (
        <div className="text-sm">
          {row.getValue("rfqCode") as string}
        </div>
      ),
      size: 120,
    },
    {
      accessorKey: "rfqRevision",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 리비전" />
      ),
      cell: ({ row }) => (
        <div className="text-sm">
          Rev. {row.getValue("rfqRevision") as number}
        </div>
      ),
      size: 120,
    },

    /** ───────────── 벤더 정보 ───────────── */
    {
      id: "vendorInfo",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더 정보" />
      ),
      cell: ({ row }) => {
        const vendorName = row.original.vendorName as string
        const vendorCode = row.original.vendorCode as string
        const vendorType = row.original.vendorCategory as string
        const vendorCountry = row.original.vendorCountry === "KR" ? "D":"F" 
        const businessSize = row.original.vendorBusinessSize as string
        
        return (
          <div className="space-y-1">
            <div className="flex items-center gap-2">
              <Building className="h-4 w-4 text-muted-foreground" />
              <div className="font-medium">{vendorName}</div>
            </div>
            <div className="text-sm text-muted-foreground">
              {vendorCode} • {vendorType} • {vendorCountry}
            </div>
            {businessSize && (
              <Badge variant="outline" className="text-xs">
                {businessSize}
              </Badge>
            )}
          </div>
        )
      },
      size: 200,
    },

    {
      accessorKey: "cpRequestYn",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="CP" />
      ),
      cell: ({ row }) => {
        const cpRequest = row.getValue("cpRequestYn") as boolean
        return cpRequest ? (
          <Badge variant="outline" className="text-xs">
            Yes
          </Badge>
        ) : (
          <span className="text-muted-foreground text-xs">-</span>
        )
      },
      size: 60,
    },
    {
      accessorKey: "prjectGtcYn",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Project GTC" />
      ),
      cell: ({ row }) => {
        const projectGtc = row.getValue("prjectGtcYn") as boolean
        return projectGtc ? (
          <Badge variant="outline" className="text-xs">
            Yes
          </Badge>
        ) : (
          <span className="text-muted-foreground text-xs">-</span>
        )
      },
      size: 100,
    },
    {
      accessorKey: "gtcYn",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="GTC" />
      ),
      cell: ({ row }) => {
        const gtc = row.getValue("gtcYn") as boolean
        return gtc ? (
          <Badge variant="outline" className="text-xs">
            Yes
          </Badge>
        ) : (
          <span className="text-muted-foreground text-xs">-</span>
        )
      },
      size: 60,
    },
    {
      accessorKey: "gtcValidDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="GTC 유효일" />
      ),
      cell: ({ row }) => {
        const gtcValidDate = row.getValue("gtcValidDate") as string
        return gtcValidDate ? (
          <div className="text-sm">
            {gtcValidDate}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 100,
    },

    {
      accessorKey: "classification",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선급" />
      ),
      cell: ({ row }) => {
        const classification = row.getValue("classification") as string
        return classification ? (
          <div className="text-sm font-medium max-w-[120px] truncate" title={classification}>
            {classification}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 120,
    },

    {
      accessorKey: "sparepart",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Spare Part" />
      ),
      cell: ({ row }) => {
        const sparepart = row.getValue("sparepart") as string
        return sparepart ? (
          <Badge variant="outline" className="text-xs">
            {sparepart}
          </Badge>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 100,
    },
  
    {
      id: "incoterms",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Incoterms" />
      ),
      cell: ({ row }) => {
        const code = row.original.incotermsCode as string
        const description = row.original.incotermsDescription as string
        
        return code ? (
          <div className="space-y-1">
            <Badge variant="outline">{code}</Badge>
            {description && (
              <div className="text-xs text-muted-foreground max-w-[150px] truncate" title={description}>
                {description}
              </div>
            )}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 120,
    },

    /** ───────────── 날짜 정보 ───────────── */
    {
      accessorKey: "validDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="유효일" />
      ),
      cell: ({ row }) => {
        const validDate = row.getValue("validDate") as Date
        return validDate ? (
          <div className="text-sm">
            {formatDate(validDate)}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 100,
    },
    {
      accessorKey: "dueDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="마감일" />
      ),
      cell: ({ row }) => {
        const dueDate = row.getValue("dueDate") as Date
        const isOverdue = dueDate && new Date(dueDate) < new Date()
        
        return dueDate ? (
          <div className={`${isOverdue ? 'text-red-600' : ''}`}>
            <div className="font-medium">{formatDate(dueDate)}</div>
            {isOverdue && (
              <div className="text-xs text-red-600">지연</div>
            )}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 120,
    },
    {
      accessorKey: "returnYn",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 회신여부" />
      ),
      cell: ({ row }) => {
        const returnFlag = row.getValue("returnYn") as boolean
        return returnFlag ? (
          <Badge variant="outline" className="text-xs">
            Yes
          </Badge>
        ) : (
          <span className="text-muted-foreground text-xs">-</span>
        )
      },
      size: 70,
    },
    {
      accessorKey: "returnRevision",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="회신 리비전" />
      ),
      cell: ({ row }) => {
        const revision = row.getValue("returnRevision") as number
        return revision > 0 ? (
          <Badge variant="outline">
            Rev. {revision}
          </Badge>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 80,
    },

    {
      accessorKey: "shortList",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Short List" />
      ),
      cell: ({ row }) => {
        const shortList = row.getValue("shortList") as boolean
        return shortList ? (
          <Badge variant="secondary" className="text-xs">
            <CheckCircle2 className="h-3 w-3 mr-1" />
            Yes
          </Badge>
        ) : (
          <span className="text-muted-foreground text-xs">-</span>
        )
      },
      size: 90,
    },

    /** ───────────── 등록/수정 정보 ───────────── */
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록일" />
      ),
      cell: ({ row }) => {
        const created = row.getValue("createdAt") as Date
        const updated = row.original.updatedAt as Date
        
        return (
          <div className="space-y-1">
            <div className="text-sm">{formatDate(created)}</div>
            {updated && new Date(updated) > new Date(created) && (
              <div className="text-xs text-blue-600">
                수정: {formatDate(updated, "KR")}
              </div>
            )}
          </div>
        )
      },
      size: 120,
    },

    /** ───────────── 액션 ───────────── */
    {
      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-48">
              <DropdownMenuItem>
                <MessageSquare className="mr-2 h-4 w-4" />
                벤더 응답 보기
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              {setRowAction && (
                <>
                  <DropdownMenuItem
                    onSelect={() => setRowAction({ row, type: "update" })}
                  >
                    <Edit className="mr-2 h-4 w-4" />
                    수정
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onSelect={() => setRowAction({ row, type: "delete" })}
                  >
                    <Trash className="mr-2 h-4 w-4" />
                    삭제
                    <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
                  </DropdownMenuItem>
                </>
              )}

            </DropdownMenuContent>
          </DropdownMenu>
        )
      },
      size: 40,
    },
  ]
}