"use client"

import * as React from "react"
import { type ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Eye, Edit, MoreHorizontal, FileX
} from "lucide-react"

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { BiddingListItem } from "@/db/schema"
import { DataTableRowAction } from "@/types/table"

// BiddingListItem에 manager 정보 추가
type BiddingListItemWithManagerCode = BiddingListItem & {
  bidPicName?: string | null
  supplyPicName?: string | null
}
import {
  biddingStatusLabels,
  contractTypeLabels,
  biddingTypeLabels,
  biddingNoticeTypeLabels,
} from "@/db/schema"
import { formatDate } from "@/lib/utils"

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

// 상태별 배지 색상
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case 'bidding_generated':
      return 'outline'
    case 'request_for_quotation':
    case 'received_quotation':
      return 'secondary'
    case 'set_target_price':
    case 'bidding_opened':
      return 'default'
    case 'bidding_closed':
    case 'evaluation_of_bidding':
      return 'default'
    case 'vendor_selected':
      return 'default'
    case 'bidding_disposal':
      return 'destructive'
    default:
      return 'outline'
  }
}

export function getBiddingsColumns({ setRowAction }: GetColumnsProps): ColumnDef<BiddingListItemWithManagerCode>[] {

  return [
    // ═══════════════════════════════════════════════════════════════
    // 선택 및 기본 정보
    // ═══════════════════════════════════════════════════════════════
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
          onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
          aria-label="select all"
          className="translate-y-0.5"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(v) => row.toggleSelected(!!v)}
          aria-label="select row"
          className="translate-y-0.5"
        />
      ),
      size: 40,
      enableSorting: false,
      enableHiding: false,
    },

    // ░░░ 입찰 No. ░░░
    {
      accessorKey: "biddingNumber",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰 No." />,
      cell: ({ row }) => (
        <div className="font-mono text-sm">
          {row.original.biddingNumber}
          {/* {row.original.revision > 0 && (
            <span className="ml-1 text-xs text-muted-foreground">
              Rev.{row.original.revision}
            </span>
          )} */}
        </div>
      ),
      size: 120,
      meta: { excelHeader: "입찰 No." },
    },

    // ░░░ 원입찰번호 ░░░
    {
      accessorKey: "originalBiddingNumber",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="원입찰번호" />,
      cell: ({ row }) => (
        <div className="font-mono text-sm">
          {row.original.originalBiddingNumber || '-'}
        </div>
      ),
      size: 120,
      meta: { excelHeader: "원입찰번호" },
    },
    // ░░░ 프로젝트명 ░░░
    {
      accessorKey: "projectName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="프로젝트 No." />,
      cell: ({ row }) => (
        <div className="truncate max-w-[150px]" title={row.original.projectName || ''}>
          {row.original.projectName || '-'}
        </div>
      ),
      size: 150,
      meta: { excelHeader: "프로젝트 No." },
    },
    // ░░░ 입찰명 ░░░
    {
      accessorKey: "title",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰명" />,
      cell: ({ row }) => (
        <div className="truncate max-w-[200px]" title={row.original.title}>
          <Button
            variant="link"
            className="p-0 h-auto font-bold underline"
            onClick={() => setRowAction({ row, type: "view" })}
          >
            <div className="whitespace-pre-line">
              {row.original.title}
            </div>
          </Button>
        </div>
      ),
      size: 200,
      meta: { excelHeader: "입찰명" },
    },
    // ░░░ 계약구분 ░░░
    {
      accessorKey: "contractType",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약구분" />,
      cell: ({ row }) => (
        <Badge variant="outline">
          {contractTypeLabels[row.original.contractType]}
        </Badge>
      ),
      size: 100,
      meta: { excelHeader: "계약구분" },
    },
    // ░░░ 입찰상태 ░░░
    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="진행상태" />,
      cell: ({ row }) => (
        <Badge variant={getStatusBadgeVariant(row.original.status)}>
          {biddingStatusLabels[row.original.status]}
        </Badge>
      ),
      size: 120,
      meta: { excelHeader: "진행상태" },
    },
    // ░░░ 입찰유형 ░░░
    {
      accessorKey: "biddingType",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰유형" />,
      cell: ({ row }) => (
        <Badge variant="secondary">
          {biddingTypeLabels[row.original.biddingType]}
        </Badge>
      ),
      size: 100,
      meta: { excelHeader: "입찰유형" },
    },

    // ░░░ 통화 ░░░
    {
      accessorKey: "currency",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="통화" />,
      cell: ({ row }) => (
        <span className="font-mono text-sm">{row.original.currency}</span>
      ),
      size: 60,
      meta: { excelHeader: "통화" },
    },

    // ░░░ 예산 ░░░
    {
      accessorKey: "budget",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="예산" />,
      cell: ({ row }) => (
        <span className="text-sm font-medium">
          {row.original.budget}
        </span>
      ),
      size: 120,
      meta: { excelHeader: "예산" },
    },

    // ░░░ 내정가 ░░░
    {
      accessorKey: "targetPrice",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="내정가" />,
      cell: ({ row }) => (
        <span className="text-sm font-medium text-orange-600">
          {row.original.targetPrice}
        </span>
      ),
      size: 120,
      meta: { excelHeader: "내정가" },
    },
    // ░░░ 입찰담당자 ░░░
    {
      accessorKey: "bidPicName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰담당자" />,
      cell: ({ row }) => {
        const name = row.original.bidPicName || "-";
        return name;
      },
      size: 100,
      meta: { excelHeader: "입찰담당자" },
    },
    
    // ░░░ 입찰등록일 ░░░
    {
      accessorKey: "biddingRegistrationDate",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰등록일" />,
      cell: ({ row }) => (
        <span className="text-sm">{formatDate(row.original.biddingRegistrationDate , "KR")}</span>
      ),
      size: 100,
      meta: { excelHeader: "입찰등록일" },
    },
    // ░░░ 입찰서제출기간 ░░░
    {
      id: "submissionPeriod",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰서제출기간" />,
      cell: ({ row }) => {
        const startDate = row.original.submissionStartDate
        const endDate = row.original.submissionEndDate
        
        if (!startDate || !endDate) return <span className="text-muted-foreground">-</span>
        
        const now = new Date().toString()
        console.log(now, "now")
        const startIso = new Date(startDate).toISOString()
        const endIso = new Date(endDate).toISOString()
        
        const isActive = new Date(now) >= new Date(startIso) && new Date(now) <= new Date(endIso)
        console.log(isActive, "isActive")
        const isPast = new Date(now) > new Date(endIso)
        console.log(isPast, "isPast")
        return (
          <div className="text-xs">
            <div className={`${isActive ? 'text-green-600 font-medium' : isPast ? 'text-red-600' : 'text-gray-600'}`}>
              {new Date(startDate).toISOString().slice(0, 16).replace('T', ' ')} ~ {new Date(endDate).toISOString().slice(0, 16).replace('T', ' ')}
            </div>
            {isActive && (
              <Badge variant="default" className="text-xs mt-1">진행중</Badge>
            )}
          </div>
        )
      },
      size: 140,
      meta: { excelHeader: "입찰서제출기간" },
    },
    // ░░░ 사양설명회 ░░░
    {
      accessorKey: "hasSpecificationMeeting",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="사양설명회" />,
      cell: ({ row }) => {
        const hasMeeting = row.original.hasSpecificationMeeting
        
        return (
          <Button
            variant="ghost"
            size="sm"
            className={`p-1 h-auto ${hasMeeting ? 'text-blue-600' : 'text-gray-400'}`}
            onClick={() => hasMeeting && setRowAction({ row, type: "specification_meeting" })}
            disabled={!hasMeeting}
          >
            {hasMeeting ? 'Yes' : 'No'}
          </Button>
        )
      },
      size: 100,
      meta: { excelHeader: "사양설명회" },
    },

    // ░░░ 등록자 ░░░

    {
      accessorKey: "updatedBy",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="등록자" />,
      cell: ({ row }) => (
        <span className="text-sm">{row.original.updatedBy || '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "등록자" },
    },
    // 등록일시
    {
      accessorKey: "updatedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="등록일시" />,
      cell: ({ row }) => (
        <span className="text-sm">{formatDate(row.original.updatedAt, "KR")}</span>
      ),
      size: 100,
      meta: { excelHeader: "등록일시" },
    },
    // ═══════════════════════════════════════════════════════════════
    // PR 정보
    // ═══════════════════════════════════════════════════════════════
    // {
    //   header: "PR 정보",
    //   columns: [
    //     {
    //       accessorKey: "prNumber",
    //       header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="PR No." />,
    //       cell: ({ row }) => (
    //         <span className="font-mono text-sm">{row.original.prNumber || '-'}</span>
    //       ),
    //       size: 100,
    //       meta: { excelHeader: "PR No." },
    //     },

    //     {
    //       accessorKey: "hasPrDocument",
    //       header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="PR 문서" />,
    //       cell: ({ row }) => {
    //         const hasPrDoc = row.original.hasPrDocument
            
    //         return (
    //           <Button
    //             variant="ghost"
    //             size="sm"
    //             className={`p-1 h-auto ${hasPrDoc ? 'text-blue-600' : 'text-gray-400'}`}
    //             onClick={() => hasPrDoc && setRowAction({ row, type: "pr_documents" })}
    //             disabled={!hasPrDoc}
    //           >
    //             {hasPrDoc ? 'Yes' : 'No'}
    //           </Button>
    //         )
    //       },
    //       size: 80,
    //       meta: { excelHeader: "PR 문서" },
    //     },
    //   ]
    // },

    // ░░░ 비고 ░░░
    {
      accessorKey: "remarks",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="비고" />,
      cell: ({ row }) => (
        <div className="truncate max-w-[150px]" title={row.original.remarks || ''}>
          {row.original.remarks || '-'}
        </div>
      ),
      size: 150,
      meta: { excelHeader: "비고" },
    },

    // ═══════════════════════════════════════════════════════════════
    // 액션
    // ═══════════════════════════════════════════════════════════════
    {
      id: "actions",
      header: "액션",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">메뉴 열기</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => setRowAction({ row, type: "view" })}>
              <Eye className="mr-2 h-4 w-4" />
              상세보기
            </DropdownMenuItem>
            {/* <DropdownMenuItem
              onClick={() => setRowAction({ row, type: "update" })}
              disabled={['bidding_opened', 'bidding_closed', 'vendor_selected'].includes(row.original.status)}
            >
              <Edit className="mr-2 h-4 w-4" />
              수정
              {['bidding_opened', 'bidding_closed', 'vendor_selected'].includes(row.original.status) && (
                <span className="text-xs text-muted-foreground ml-2">(수정 불가)</span>
              )}
            </DropdownMenuItem> */}
            {/* <DropdownMenuSeparator />
            <DropdownMenuItem
              onClick={() => setRowAction({ row, type: "bid_closure" })}
              disabled={row.original.status !== 'bidding_disposal'}
            >
              <FileX className="mr-2 h-4 w-4" />
              폐찰하기
              {row.original.status !== 'bidding_disposal' && (
                <span className="text-xs text-muted-foreground ml-2">(유찰 시에만 가능)</span>
              )}
            </DropdownMenuItem> */}
            {/* <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => setRowAction({ row, type: "copy" })}>
              <Package className="mr-2 h-4 w-4" />
              복사 생성
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setRowAction({ row, type: "manage_companies" })}>
              <Users className="mr-2 h-4 w-4" />
              참여업체 관리
            </DropdownMenuItem> */}
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      size: 50,
      enableSorting: false,
      enableHiding: false,
    },
  ]
}