'use client'

import * as React from 'react'
import { createColumnHelper } from '@tanstack/react-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  CheckCircle,
  XCircle,
  FileText,
  MoreHorizontal,
  Calendar,
  User,
  Calculator,
  Paperclip,
  AlertTriangle
} from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { biddingStatusLabels, contractTypeLabels } from '@/db/schema'
import { PartnersBiddingListItem } from '../detail/service'
import { Checkbox } from '@/components/ui/checkbox'

const columnHelper = createColumnHelper<PartnersBiddingListItem>()

interface PartnersBiddingListColumnsProps {
  setRowAction?: (action: { type: string; row: { original: PartnersBiddingListItem } }) => void
}

export function getPartnersBiddingListColumns({ setRowAction }: PartnersBiddingListColumnsProps = {}) {
  return [
    // select 버튼
    {
      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.
    columnHelper.accessor('biddingNumber', {
      header: '입찰 No.',
      cell: ({ row }) => {
        const biddingNumber = row.original.biddingNumber
        const revision = row.original.revision
        return (
          <div className="font-mono text-sm">
            <div>{biddingNumber}</div>
              <div className="text-muted-foreground">Rev. {revision ?? 0}</div>
          </div>
        )
      },
    }),

    // 입찰상태
    columnHelper.accessor('status', {
      header: '입찰상태',
      cell: ({ row }) => {
        const status = row.original.status
        return (
          <Badge variant={
            status === 'bidding_disposal' ? 'destructive' :
            status === 'vendor_selected' ? 'default' :
            status === 'bidding_generated' ? 'secondary' :
            'outline'
          }>
            {biddingStatusLabels[status] || status}
          </Badge>
        )
      },
    }),

    // 긴급여부
    columnHelper.accessor('isUrgent', {
      header: '긴급여부',
      cell: ({ row }) => {
        const isUrgent = row.original.isUrgent

        return isUrgent ? (
          <div className="flex items-center gap-1">
            <AlertTriangle className="h-4 w-4 text-red-600" />
            <Badge variant="destructive" className="text-xs">
              긴급
            </Badge>
          </div>
        ) : (
          <div className="flex items-center gap-1">
            <CheckCircle className="h-4 w-4 text-green-600" />
            <span className="text-xs text-muted-foreground">일반</span>
          </div>
        )
      },
    }),

    // 첨부파일
    columnHelper.display({
      id: 'attachments',
      header: 'SHI 첨부파일',
      cell: ({ row }) => {
        const handleViewDocumentsClick = (e: React.MouseEvent) => {
          e.stopPropagation()
          if (setRowAction) {
            setRowAction({
              type: 'view-documents',
              row: { original: row.original }
            })
          }
        }

        return (
          <Button
            variant="ghost"
            size="sm"
            className="p-1 h-8 w-8"
            onClick={handleViewDocumentsClick}
            title="첨부파일 보기"
          >
            <Paperclip className="h-4 w-4 text-blue-600" />
          </Button>
        )
      },
      size: 80,
      enableSorting: false,
    }),

    // 액션 (드롭다운 메뉴)
    columnHelper.display({
      id: 'actions',
      header: '액션',
      cell: ({ row }) => {
        const handleView = () => {
          if (setRowAction) {
            setRowAction({
              type: 'view',
              row: { original: row.original }
            })
          }
        }

        const handlePreQuote = () => {
          if (setRowAction) {
            setRowAction({
              type: 'pre-quote',
              row: { original: row.original }
            })
          }
        }

        const biddingStatus = row.original.status
        const isClosed = biddingStatus === 'bidding_closed' || biddingStatus === 'vendor_selected' || biddingStatus === 'bidding_disposal'

        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
              >
                <MoreHorizontal className="h-4 w-4" />
                <span className="sr-only">메뉴 열기</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-[160px]">
              <DropdownMenuItem onClick={handleView}>
                <FileText className="mr-2 h-4 w-4" />
                입찰 상세보기
              </DropdownMenuItem>
              {!isClosed && (
                <DropdownMenuItem onClick={handlePreQuote}>
                  <Calculator className="mr-2 h-4 w-4" />
                  사전견적하기
                </DropdownMenuItem>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        )
      },
    }),

    // 품목명
    columnHelper.accessor('itemName', {
      header: '품목명',
      cell: ({ row }) => (
        <div className="max-w-32 truncate" title={row.original.itemName}>
          {row.original.itemName}
        </div>
      ),
    }),

    // 입찰명
    columnHelper.accessor('title', {
      header: '입찰명',
      cell: ({ row }) => (
        <div className="max-w-48 truncate" title={row.original.title}>
          {row.original.title}
        </div>
      ),
    }),

    // 사양설명회
    columnHelper.accessor('isAttendingMeeting', {
      header: '사양설명회',
      cell: ({ row }) => {
        const isAttending = row.original.isAttendingMeeting
        if (isAttending === null) {
          return <div className="text-muted-foreground text-center">-</div>
        }
        return isAttending ? (
          <CheckCircle className="h-5 w-5 text-green-600 mx-auto" />
        ) : (
          <XCircle className="h-5 w-5 text-red-600 mx-auto" />
        )
      },
    }),

    // 사전견적 참여의사
    columnHelper.accessor('isPreQuoteParticipated', {
      header: '사전견적 참여의사',
      cell: ({ row }) => {
        const participated = row.original.isPreQuoteParticipated
        if (participated === null) {
          return <Badge variant="outline">미결정</Badge>
        }
        return (
          <Badge variant={participated ? 'default' : 'destructive'}>
            {participated ? '참여' : '미참여'}
          </Badge>
        )
      },
    }),

    // 입찰 참여의사
    columnHelper.accessor('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>
        )
      },
    }),

    // 계약구분
    columnHelper.accessor('contractType', {
      header: '계약구분',
      cell: ({ row }) => (
        <div>{contractTypeLabels[row.original.contractType] || row.original.contractType}</div>
      ),
    }),

    // 입찰기간
    columnHelper.accessor('submissionStartDate', {
      header: '입찰기간',
      cell: ({ row }) => {
        const startDate = row.original.submissionStartDate
        const endDate = row.original.submissionEndDate
        if (!startDate || !endDate) {
          return <div className="text-muted-foreground">-</div>
        }
        return (
          <div className="text-sm">
            <div>{formatDate(startDate, 'KR')}</div>
            <div className="text-muted-foreground">~</div>
            <div>{formatDate(endDate, 'KR')}</div>
          </div>
        )
      },
    }),

    // 사전견적 마감일
    columnHelper.accessor('preQuoteDeadline', {
      header: '사전견적 마감일',
      cell: ({ row }) => {
        const deadline = row.original.preQuoteDeadline
        if (!deadline) {
          return <div className="text-muted-foreground">-</div>
        }
        
        const now = new Date()
        const deadlineDate = new Date(deadline)
        const isExpired = deadlineDate < now
        
        return (
          <div className={`text-sm flex items-center gap-1 ${isExpired ? 'text-red-600' : ''}`}>
            <Calendar className="w-4 h-4" />
            <span>{formatDate(deadline, 'KR')}</span>
            {isExpired && (
              <Badge variant="destructive" className="text-xs">
                마감
              </Badge>
            )}
          </div>
        )
      },
    }),

    // 계약기간
    columnHelper.accessor('contractStartDate', {
      header: '계약기간',
      cell: ({ row }) => {
        const startDate = row.original.contractStartDate
        const endDate = row.original.contractEndDate

        if (!startDate || !endDate) {
          return <div className="max-w-24 truncate">-</div>
        }

        return (
          <div className="max-w-24 truncate" title={`${formatDate(startDate, 'KR')} ~ ${formatDate(endDate, 'KR')}`}>
            {formatDate(startDate, 'KR')} ~ {formatDate(endDate, 'KR')}
          </div>
        )
      },
    }),

    // 참여회신 마감일
    columnHelper.accessor('responseDeadline', {
      header: '참여회신 마감일',
      cell: ({ row }) => {
        const deadline = row.original.responseDeadline
        if (!deadline) {
          return <div className="text-muted-foreground">-</div>
        }
        return <div className="text-sm">{formatDate(deadline, 'KR')}</div>
      },
    }),

    // 입찰제출일
    columnHelper.accessor('submissionDate', {
      header: '입찰제출일',
      cell: ({ row }) => {
        const date = row.original.submissionDate
        if (!date) {
          return <div className="text-muted-foreground">-</div>
        }
        return <div className="text-sm">{formatDate(date, 'KR')}</div>
      },
    }),

    // 입찰담당자
    columnHelper.accessor('managerName', {
      header: '입찰담당자',
      cell: ({ row }) => {
        const name = row.original.managerName
        const email = row.original.managerEmail
        if (!name) {
          return <div className="text-muted-foreground">-</div>
        }
        return (
          <div className="flex items-center gap-1">
            <User className="h-4 w-4" />
            <div>
              <div className="text-sm">{name}</div>
              {email && (
                <div className="text-xs text-muted-foreground truncate max-w-32" title={email}>
                  {email}
                </div>
              )}
            </div>
          </div>
        )
      },
    }),

    // 최종수정일
    columnHelper.accessor('updatedAt', {
      header: '최종수정일',
      cell: ({ row }) => (
        <div className="text-sm">{formatDate(row.original.updatedAt, 'KR')}</div>
      ),
    }),


  ]
}
