"use client"

import * as React from "react"
import { ColumnDef } from "@tanstack/react-table"
import { formatDate } from "@/lib/utils"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import {
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"

// RFQ 아이템 정보 타입
export interface RfqItemInfo {
  itemCode: string
  workType: string
  itemList: string
  subItemList: string
  shipTypes: string
}

// Accepted Quotation 타입 정의
export interface AcceptedQuotationItem {
  id: number
  uniqueKey: string // 확장된 데이터의 유니크 키
  rfqId: number
  vendorId: number
  quotationVersion: number | null
  totalPrice: string | null
  currency: string | null
  validUntil: Date | null
  status: string
  remark: string | null
  submittedAt: Date | null
  acceptedAt: Date | null
  createdAt: Date
  updatedAt: Date
  
  // RFQ 정보
  rfqCode: string | null
  rfqType: string | null
  description: string | null
  dueDate: Date | null
  rfqStatus: string | null
  materialCode: string | null
  
  // Vendor 정보
  vendorName: string
  vendorCode: string | null
  vendorEmail: string | null
  vendorCountry: string | null
  vendorFlags: {
    isCustomerPreferred?: boolean;
    isNewDiscovery?: boolean;
    isProjectApproved?: boolean;
    isShiProposal?: boolean;
  } | null // 벤더 플래그 (JSON)
  
  // Project 정보
  projNm: string | null
  pspid: string | null
  sector: string | null
  kunnrNm: string | null // 선주명
  ptype: string | null // 선종코드
  ptypeNm: string | null // 선종명
  pjtType: string | null // 프로젝트 타입
  
  // RFQ 아이템 정보
  rfqItems: RfqItemInfo[]
  
  // 확장된 아이템 정보
  itemIndex: number
  totalItems: number
  isExpanded: boolean
  itemCode: string
  workType: string
  itemList: string
  subItemList: string
  shipTypes: string
}

export function getColumns(): ColumnDef<AcceptedQuotationItem>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<AcceptedQuotationItem> = {
    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,
  }

  // ----------------------------------------------------------------
  // 3) 데이터 컬럼들 정의
  // ----------------------------------------------------------------
  const dataColumns: ColumnDef<AcceptedQuotationItem>[] = [
    // 프로젝트 타입
    {
      accessorKey: "pjtType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="프로젝트 타입" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.original.pjtType || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "프로젝트 타입",
      },
    },
    // 프로젝트 코드
    {
      accessorKey: "pspid",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="프로젝트 코드" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.original.pspid || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "프로젝트 코드",
      },
    },
    // 프로젝트명
    {
      accessorKey: "projNm",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="프로젝트명" />
      ),
      cell: ({ row }) => (
        <div className="max-w-32 truncate">
          {row.original.projNm || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "프로젝트명",
      },
    },
    // 선주명
    {
      accessorKey: "kunnrNm",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선주명" />
      ),
      cell: ({ row }) => (
        <div className="max-w-32 truncate">
          {row.original.kunnrNm || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "선주명",
      },
    },
    // 선종코드
    {
      accessorKey: "ptype",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선종코드" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.original.ptype || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "선종코드",
      },
    },
        // 공종
        {
          accessorKey: "workType",
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="공종" />
          ),
          cell: ({ row }) => {
            return (
              <div className="max-w-32 truncate">
                {row.original.workType || "-"}
              </div>
            );
          },
          enableSorting: false,
          enableHiding: true,
          meta: {
            excelHeader: "공종",
          },
        },
    // RFQ 코드
    {
      accessorKey: "rfqCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 코드" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.original.rfqCode || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "RFQ 코드",
      },
    },
    // RFQ 제목
    {
      accessorKey: "description",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 제목" />
      ),
      cell: ({ row }) => (
        <div className="max-w-32 truncate">
          {row.original.description || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "RFQ 제목",
      },
    },
    // 자재그룹
    {
      accessorKey: "materialGroup",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재그룹" />
      ),
      cell: ({ row }) => {
        return (
          <div className="max-w-32 truncate">
            {row.original.itemCode || "-"}
          </div>
        );
      },
      enableSorting: false,
      enableHiding: true,
      meta: {
        excelHeader: "자재그룹",
      },
    },

    // 선종
    {
      accessorKey: "shipType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선종" />
      ),
      cell: ({ row }) => {
        return (
          <div className="max-w-32 truncate">
            {row.original.shipTypes || "-"}
          </div>
        );
      },
      enableSorting: false,
      enableHiding: true,
      meta: {
        excelHeader: "선종",
      },
    },
    // 자재명
    {
      accessorKey: "itemName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재명" />
      ),
      cell: ({ row }) => {
        return (
          <div className="max-w-32 truncate">
            {row.original.itemList || "-"}
          </div>
        );
      },
      enableSorting: false,
      enableHiding: true,
      meta: {
        excelHeader: "자재명",
      },
    },
    // 자재명(상세)
    {
      accessorKey: "itemDetail",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재명(상세)" />
      ),
      cell: ({ row }) => {
        return (
          <div className="max-w-32 truncate">
            {row.original.subItemList || "-"}
          </div>
        );
      },
      enableSorting: false,
      enableHiding: true,
      meta: {
        excelHeader: "자재명(상세)",
      },
    },
    // 협력업체명
    {
      accessorKey: "vendorName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체명" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.original.vendorName}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "협력업체명",
      },
    },
                // 벤더 유형
            {
              accessorKey: "vendorFlags",
              header: ({ column }) => (
                <DataTableColumnHeaderSimple column={column} title="벤더 유형" />
              ),
              cell: ({ row }) => {
                const vendorFlags = row.original.vendorFlags;
                
                if (!vendorFlags) {
                  return <div className="text-muted-foreground">-</div>;
                }
                
                const activeFlags = [];
                
                if (vendorFlags.isCustomerPreferred) {
                  activeFlags.push({ key: "isCustomerPreferred", label: "고객선호", variant: "outline" as const });
                }
                if (vendorFlags.isNewDiscovery) {
                  activeFlags.push({ key: "isNewDiscovery", label: "신규발굴", variant: "outline" as const });
                }
                if (vendorFlags.isProjectApproved) {
                  activeFlags.push({ key: "isProjectApproved", label: "프로젝트승인", variant: "outline" as const });
                }
                if (vendorFlags.isShiProposal) {
                  activeFlags.push({ key: "isShiProposal", label: "SHI제안", variant: "outline" as const });
                }
                
                if (activeFlags.length === 0) {
                  return <div className="text-muted-foreground">-</div>;
                }
                
                return (
                  <div className="flex flex-wrap gap-1">
                    {activeFlags.map((flag) => (
                      <Badge key={flag.key} variant={flag.variant} className="text-xs">
                        {flag.label}
                      </Badge>
                    ))}
                  </div>
                );
              },
              enableSorting: true,
              enableHiding: true,
              meta: {
                excelHeader: "협력업체 유형",
              },
            },
    // 협력업체 코드
    {
      accessorKey: "vendorCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체 코드" />
      ),
      cell: ({ row }) => (
        <div>
          {row.original.vendorCode || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "협력업체 코드",
      },
    },
    // 협력업체 국가
    {
      accessorKey: "vendorCountry",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체 국가" />
      ),
      cell: ({ row }) => (
        <div>
          {row.original.vendorCountry || "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "협력업체 국가",
      },
    },
        // 총 금액
        {
          accessorKey: "totalPrice",
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="총 금액" />
          ),
          cell: ({ row }) => {
            const price = row.original.totalPrice;
            const currency = row.original.currency || "USD";
            return (
              <div className="text-right font-medium">
                {price ? `${Number(price).toLocaleString()} ${currency}` : "-"}
              </div>
            );
          },
          enableSorting: true,
          enableHiding: true,
          meta: {
            excelHeader: "총 금액",
          },
        },
        // 상태
        {
          accessorKey: "status",
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="상태" />
          ),
          cell: ({ row }) => {
            const status = row.original.status;
            let badgeVariant: "default" | "secondary" | "destructive" | "outline" = "default";
            let badgeClassName = "";
            
            if (status === "Submitted") {
              badgeVariant = "secondary";
              badgeClassName = "bg-blue-100 text-blue-800";
            } else if (status === "Accepted") {
              badgeVariant = "default";
              badgeClassName = "bg-green-100 text-green-800";
            } else {
              badgeVariant = "outline";
              badgeClassName = "bg-gray-100 text-gray-800";
            }
            
            return (
              <Badge variant={badgeVariant} className={badgeClassName}>
                {status}
              </Badge>
            );
          },
          enableSorting: true,
          enableHiding: true,
          meta: {
            excelHeader: "상태",
          },
        },
    // RFQ 제출일
    {
      accessorKey: "submittedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="RFQ 제출일" />
      ),
      cell: ({ row }) => (
        <div>
          {row.original.submittedAt ? formatDate(row.original.submittedAt) : "-"}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "RFQ 제출일",
      },
    },
  ]

  return [selectColumn, ...dataColumns]
} 