"use client"

import * as React from "react"
import { type ColumnDef } from "@tanstack/react-table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Eye, Calendar, FileX, DollarSign, AlertTriangle, RefreshCw, FileText
} from "lucide-react"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import {
  biddingStatusLabels,
  contractTypeLabels,
} from "@/db/schema"
import { formatDate } from "@/lib/utils"
import { DataTableRowAction } from "@/types/table"
import { downloadFile } from "@/lib/file-download"

type BiddingFailureItem = {
  id: number
  biddingNumber: string
  originalBiddingNumber: string | null
  title: string
  status: string
  contractType: string
  prNumber: string | null

  // 가격 정보
  targetPrice: number | null
  currency: string | null

  // 일정 정보
  biddingRegistrationDate: Date | null
  submissionStartDate: Date | null
  submissionEndDate: Date | null

  // 담당자 정보
  bidPicName: string | null
  supplyPicName: string | null

  // 유찰 정보
  disposalDate: Date | null // 유찰일
  disposalUpdatedAt: Date | null // 폐찰수정일
  disposalUpdatedBy: string | null // 폐찰수정자

  // 폐찰 정보
  closureReason: string | null // 폐찰사유
  closureDocuments: {
    id: number
    fileName: string
    originalFileName: string
    filePath: string
  }[] // 폐찰 첨부파일들

  // 기타 정보
  createdBy: string | null
  createdAt: Date | null
  updatedAt: Date | null
  updatedBy: string | null
}

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

// 상태별 배지 색상
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case 'bidding_disposal':
      return 'destructive'
    default:
      return 'outline'
  }
}

// 금액 포맷팅
const formatCurrency = (amount: string | number | null, currency = 'KRW') => {
  if (!amount) return '-'

  const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount
  if (isNaN(numAmount)) return '-'

  return new Intl.NumberFormat('ko-KR', {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(numAmount)
}

export function getBiddingsFailureColumns({ setRowAction }: GetColumnsProps): ColumnDef<BiddingFailureItem>[] {

  return [
    // ░░░ 선택 ░░░
    {
      id: "select",
      header: "",
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => {
            // single select 모드에서는 다른 행들의 선택을 해제
            row.toggleSelected(!!value)
          }}
          aria-label="행 선택"
        />
      ),
      size: 50,
      enableSorting: false,
      enableHiding: false,
    },

    // ░░░ 입찰번호 ░░░
    {
      accessorKey: "biddingNumber",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰번호" />,
      cell: ({ row }) => (
        <div className="font-mono text-sm">
          {row.original.biddingNumber}
        </div>
      ),
      size: 120,
      meta: { excelHeader: "입찰번호" },
    },

    // ░░░ 입찰명 ░░░
    {
      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 text-left justify-start font-bold underline"
            onClick={() => setRowAction({ row, type: "view" })}
          >
            <div className="whitespace-pre-line">
              {row.original.title}
            </div>
          </Button>
        </div>
      ),
      size: 200,
      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: "contractType",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약구분" />,
      cell: ({ row }) => (
        <Badge variant="outline">
          {contractTypeLabels[row.original.contractType]}
        </Badge>
      ),
      size: 100,
      meta: { excelHeader: "계약구분" },
    },

    // ░░░ 내정가 ░░░
    {
      accessorKey: "targetPrice",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="내정가" />,
      cell: ({ row }) => {
        const price = row.original.targetPrice
        const currency = row.original.currency || 'KRW'

        return (
          <div className="text-sm font-medium text-orange-600">
            {price ? formatCurrency(price, currency) : '-'}
          </div>
        )
      },
      size: 120,
      meta: { excelHeader: "내정가" },
    },

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

    // ░░░ 입찰등록일 ░░░
    {
      accessorKey: "biddingRegistrationDate",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰등록일" />,
      cell: ({ row }) => (
        <span className="text-sm">{row.original.biddingRegistrationDate ? formatDate(row.original.biddingRegistrationDate, "KR") : '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "입찰등록일" },
    },

    // ░░░ 입찰담당자 ░░░
    {
      accessorKey: "bidPicName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="입찰담당자" />,
      cell: ({ row }) => {
        const bidPic = row.original.bidPicName
        const supplyPic = row.original.supplyPicName

        const displayName = bidPic || supplyPic || "-"
        return <span className="text-sm">{displayName}</span>
      },
      size: 100,
      meta: { excelHeader: "입찰담당자" },
    },

    // ░░░ 유찰일 ░░░
    {
      id: "disposalDate",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="유찰일" />,
      cell: ({ row }) => (
        <div className="flex items-center gap-1">
          <AlertTriangle className="h-4 w-4 text-red-500" />
          <span className="text-sm">{row.original.disposalDate ? formatDate(row.original.disposalDate, "KR") : '-'}</span>
        </div>
      ),
      size: 100,
      meta: { excelHeader: "유찰일" },
    },

    // ░░░ 폐찰일 ░░░
    {
      id: "disposalUpdatedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐찰일" />,
      cell: ({ row }) => (
        <div className="flex items-center gap-1">
          <FileX className="h-4 w-4 text-red-500" />
          <span className="text-sm">{row.original.disposalUpdatedAt ? formatDate(row.original.disposalUpdatedAt, "KR") : '-'}</span>
        </div>
      ),
      size: 100,
      meta: { excelHeader: "폐찰일" },
    },

    // ░░░ 폐찰수정자 ░░░
    {
      id: "disposalUpdatedBy",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐찰수정자" />,
      cell: ({ row }) => (
        <span className="text-sm">{row.original.disposalUpdatedBy || '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "폐찰수정자" },
    },

    // ░░░ 폐찰사유 ░░░
    {
      id: "closureReason",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐찰사유" />,
      cell: ({ row }) => (
        <div className="max-w-[200px] truncate" title={row.original.closureReason || undefined}>
          <span className="text-sm">{row.original.closureReason || '-'}</span>
        </div>
      ),
      size: 150,
      meta: { excelHeader: "폐찰사유" },
    },

    // ░░░ 폐찰첨부파일 ░░░
    {
      id: "closureDocuments",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐찰첨부파일" />,
      cell: ({ row }) => {
        const documents = row.original.closureDocuments || []

        if (documents.length === 0) {
          return <span className="text-sm text-muted-foreground">-</span>
        }

        return (
          <div className="flex flex-wrap gap-1 max-w-[200px]">
            {documents.map((doc) => (
              <Button
                key={doc.id}
                variant="link"
                size="sm"
                className="p-0 h-auto text-xs underline"
                onClick={async () => {
                  try {
                    await downloadFile(doc.filePath, doc.originalFileName)
                  } catch (error) {
                    console.error('파일 다운로드 실패:', error)
                  }
                }}
              >
                <FileText className="mr-1 h-3 w-3" />
                {doc.originalFileName}
              </Button>
            ))}
          </div>
        )
      },
      size: 200,
      meta: { excelHeader: "폐찰첨부파일" },
    },

    // ░░░ P/R번호 ░░░
    {
      accessorKey: "prNumber",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="P/R번호" />,
      cell: ({ row }) => (
        <span className="font-mono text-sm">{row.original.prNumber || '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "P/R번호" },
    },

    // ░░░ 등록자 ░░░
    {
      accessorKey: "createdBy",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="등록자" />,
      cell: ({ row }) => (
        <span className="text-sm">{row.original.createdBy || '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "최종수정자" },
    },

    // ░░░ 등록일시 ░░░
    {
      accessorKey: "createdAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="등록일시" />,
      cell: ({ row }) => (
        <span className="text-sm">{row.original.createdAt ? formatDate(row.original.createdAt, "KR") : '-'}</span>
      ),
      size: 100,
      meta: { excelHeader: "최종일시" },
    },

  ]
}
