"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 {
  MoreHorizontal, Edit, Trash2, Trophy
} from "lucide-react"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { QuotationVendor } from "@/lib/bidding/detail/service"

interface GetVendorColumnsProps {
  onEdit: (vendor: QuotationVendor) => void
  onDelete: (vendor: QuotationVendor) => void
  onSelectWinner: (vendor: QuotationVendor) => void
  onViewPriceAdjustment?: (vendor: QuotationVendor) => void
  onViewItemDetails?: (vendor: QuotationVendor) => void
  onSendBidding?: (vendor: QuotationVendor) => void
  onUpdateParticipation?: (vendor: QuotationVendor, participated: boolean) => void
}

export function getBiddingDetailVendorColumns({
  onEdit,
  onDelete,
  onSelectWinner,
  onViewPriceAdjustment,
  onViewItemDetails,
  onSendBidding,
  onUpdateParticipation
}: GetVendorColumnsProps): ColumnDef<QuotationVendor>[] {
  return [
    {
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected()}
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="모두 선택"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="행 선택"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: 'vendorName',
      header: '업체명',
      cell: ({ row }) => (
        <div className="font-medium">{row.original.vendorName}</div>
      ),
    },
    {
      accessorKey: 'vendorCode',
      header: '업체코드',
      cell: ({ row }) => (
        <div className="font-mono text-sm">{row.original.vendorCode}</div>
      ),
    },
    {
      accessorKey: 'quotationAmount',
      header: '견적금액',
      cell: ({ row }) => {
        const hasAmount = row.original.quotationAmount && Number(row.original.quotationAmount) > 0
        return (
          <div className="text-right font-mono">
            {hasAmount ? (
              <button
                onClick={() => onViewItemDetails?.(row.original)}
                className="text-primary hover:text-primary/80 hover:underline cursor-pointer"
                title="품목별 견적 상세 보기"
              >
                {Number(row.original.quotationAmount).toLocaleString()} {row.original.currency}
              </button>
            ) : (
              <span className="text-muted-foreground">- {row.original.currency}</span>
            )}
          </div>
        )
      },
    },
    {
      accessorKey: 'biddingResult',
      header: '입찰결과',
      cell: ({ row }) => {
        const isWinner = row.original.isWinner
        if (isWinner === null || isWinner === undefined) {
          return <div>미정</div>
        }
        return (
          <Badge variant={isWinner ? 'default' : 'secondary'} className={isWinner ? 'bg-green-600' : ''}>
            {isWinner ? '낙찰' : '탈락'}
          </Badge>
        )
      },
    },
    {
      accessorKey: 'awardRatio',
      header: '발주비율',
      cell: ({ row }) => (
        <div className="text-right">
          {row.original.awardRatio !== null ? `${row.original.awardRatio}%` : '-'}
        </div>
      ),
    },
    {
      accessorKey: 'isBiddingParticipated',
      header: '입찰참여',
      cell: ({ row }) => {
        const participated = row.original.isBiddingParticipated
        if (participated === null) {
          return <Badge variant="outline">대기</Badge>
        }
        return (
          <Badge variant={participated ? 'default' : 'destructive'}>
            {participated ? '응찰' : '미응찰'}
          </Badge>
        )
      },
    },
    {
      accessorKey: 'status',
      header: '상태',
      cell: ({ row }) => {
        const status = row.original.status
        const variant = status === 'selected' ? 'default' :
                       status === 'submitted' ? 'secondary' :
                       status === 'rejected' ? 'destructive' : 'outline'

        const label = status === 'selected' ? '선정' :
                     status === 'submitted' ? '제출' :
                     status === 'rejected' ? '거절' : '대기'

        return <Badge variant={variant}>{label}</Badge>
      },
    },
    {
      accessorKey: 'submissionDate',
      header: '제출일',
      cell: ({ row }) => (
        <div className="text-sm">
          {row.original.submissionDate ? new Date(row.original.submissionDate).toLocaleDateString('ko-KR') : '-'}
        </div>
      ),
    },
    {
      id: 'actions',
      header: '작업',
      cell: ({ row }) => {
        const vendor = row.original

        return (
          <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">
              <DropdownMenuLabel>작업</DropdownMenuLabel>
              <DropdownMenuItem 
                onClick={() => onEdit(vendor)}
                disabled={vendor.isBiddingParticipated !== true}
              >
                발주비율 산정
                {vendor.isBiddingParticipated !== true && (
                  <span className="text-xs text-muted-foreground ml-2">(입찰참여 필요)</span>
                )}
              </DropdownMenuItem>
              {vendor.status !== 'selected' && (
                <DropdownMenuItem 
                  onClick={() => onSelectWinner(vendor)}
                  disabled={vendor.isBiddingParticipated !== true}
                >
                  낙찰 선정
                  {vendor.isBiddingParticipated !== true && (
                    <span className="text-xs text-muted-foreground ml-2">(입찰참여 필요)</span>
                  )}
                </DropdownMenuItem>
              )}
              
              {/* 입찰 참여여부 관리 */}
              {vendor.isBiddingParticipated === null && onUpdateParticipation && (
                <>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => onUpdateParticipation(vendor, true)}>
                    응찰 설정
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => onUpdateParticipation(vendor, false)}>
                    미응찰 설정
                  </DropdownMenuItem>
                </>
              )}
              
              {/* 입찰 보내기 (응찰한 업체만) */}
              {vendor.isBiddingParticipated === true && onSendBidding && (
                <>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => onSendBidding(vendor)}>
                    입찰 보내기
                  </DropdownMenuItem>
                </>
              )}
              
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => onDelete(vendor)}
                className="text-destructive"
              >
                삭제
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        )
      },
    },
  ]
}
