"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 Link from "next/link"

import { formatDate } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { techVendorRfqHistoryColumnsConfig } from "@/config/techVendorRfqHistoryColumnsConfig"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"

export interface TechVendorRfqHistoryRow {
  id: number;
  rfqCode: string | null;
  description: string | null;
  projectCode: string | null;
  projectName: string | null;
  projectType: string | null; // 프로젝트 타입 추가
  status: string;
  totalAmount: string | null;
  currency: string | null;
  dueDate: Date | null;
  createdAt: Date;
  quotationCode: string | null;
  submittedAt: Date | null;
}

// 프로젝트 타입에 따른 RFQ 페이지 URL 생성 함수
function getRfqPageUrl(projectType: string | null, description: string | null): string {
  const baseUrls = {
    'SHIP': '/evcp/budgetary-tech-sales-ship',
    'TOP': '/evcp/budgetary-tech-sales-top', 
    'HULL': '/evcp/budgetary-tech-sales-hull'
  };

  const url = baseUrls[projectType as keyof typeof baseUrls] || '/evcp/budgetary-tech-sales-ship';
  
  // description이 있으면 search 파라미터로 추가
  if (description) {
    return `${url}?search=${encodeURIComponent(description)}`;
  }
  
  return url;
}

// 프로젝트 타입 표시 함수
function getProjectTypeDisplay(projectType: string | null): string {
  const typeMap = {
    'SHIP': '조선',
    'TOP': '해양TOP',
    'HULL': '해양HULL'
  };
  
  return typeMap[projectType as keyof typeof typeMap] || projectType || '-';
}

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TechVendorRfqHistoryRow> | null>>;
}

export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVendorRfqHistoryRow>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<TechVendorRfqHistoryRow> = {
    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<TechVendorRfqHistoryRow> = {
  //   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<TechVendorRfqHistoryRow>[] = techVendorRfqHistoryColumnsConfig.map((cfg) => {
    const column: ColumnDef<TechVendorRfqHistoryRow> = {
      accessorKey: cfg.id,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      size: cfg.size,
    }

    if (cfg.id === "rfqCode") {
      column.cell = ({ row }) => {
        const rfqCode = row.original.rfqCode
        const projectType = row.original.projectType
        if (!rfqCode) return null
        
        const rfqUrl = getRfqPageUrl(projectType, rfqCode);
        
        return (
          <Tooltip>
            <TooltipTrigger asChild>
              <Link 
                href={rfqUrl}
                className="break-words whitespace-normal line-clamp-2 hover:underline cursor-pointer"
              >
                {rfqCode}
              </Link>
            </TooltipTrigger>
            <TooltipContent side="bottom" className="max-w-[400px] whitespace-pre-wrap break-words">
              <div>
                <div className="font-medium">{rfqCode}</div>
                <div className="text-xs text-muted-foreground mt-1">
                  클릭하여 RFQ 페이지로 이동
                </div>
              </div>
            </TooltipContent>
          </Tooltip>
        )
      }
    }

    if (cfg.id === "projectType") {
      column.cell = ({ row }) => {
        const projectType = row.original.projectType
        return (
          <div className="whitespace-nowrap">
            {getProjectTypeDisplay(projectType)}
          </div>
        )
      }
    }

    if (cfg.id === "status") {
      column.cell = ({ row }) => {
        const statusVal = row.original.status
        if (!statusVal) return null
        return (
          <div className="flex items-center">
            <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 <span className="text-gray-400">-</span>
        return (
          <div className="whitespace-nowrap">
            {`${currency} ${Number(amount).toLocaleString()}`}
          </div>
        )
      }
    }

    if (cfg.id === "dueDate" || cfg.id === "createdAt") {
      column.cell = ({ row }) => {
        const dateValue = row.getValue(cfg.id) as Date
        if (!dateValue) return <span className="text-gray-400">-</span>
        return (
          <div className="whitespace-nowrap">
            {formatDate(dateValue)}
          </div>
        )
      }
    }

    if (cfg.id === "projectCode" || cfg.id === "projectName") {
      column.cell = ({ row }) => {
        const value = row.getValue(cfg.id) as string | null
        if (!value) return <span className="text-gray-400">-</span>
        return value
      }
      column.size = 100;
    }

    return column
  })

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