"use client"

import * as React from "react"
import { ClientDataTable } from "@/components/client-data-table/data-table"
import type { EnhancedVendorResponse } from "@/lib/b-rfq/service"
import { DataTableAdvancedFilterField } from "@/types/table"
import { DataTableRowAction, getColumns } from "./response-detail-columns"

interface FinalRfqResponseTableProps {
  data: EnhancedVendorResponse[]
  // ✅ 헤더 정보를 props로 받기
  statistics?: {
    total: number
    upToDate: number
    versionMismatch: number
    pending: number
    revisionRequested: number
    waived: number
  }
  showHeader?: boolean
  title?: string
}

/**
 * FinalRfqResponseTable: RFQ 응답 데이터를 표시하는 표
 */
export function FinalRfqResponseTable({ 
  data, 
  statistics,
  showHeader = true,
  title = "첨부파일별 응답 현황"
}: FinalRfqResponseTableProps) {
  const [rowAction, setRowAction] = 
    React.useState<DataTableRowAction<EnhancedVendorResponse> | null>(null)

  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 고급 필터 필드 정의
  const advancedFilterFields: DataTableAdvancedFilterField<EnhancedVendorResponse>[] = [
    {
      id: "effectiveStatus",
      label: "상태",
      type: "select",
      options: [
        { label: "미응답", value: "NOT_RESPONDED" },
        { label: "최신", value: "UP_TO_DATE" },
        { label: "업데이트 필요", value: "VERSION_MISMATCH" },
        { label: "수정요청", value: "REVISION_REQUESTED" },
        { label: "포기", value: "WAIVED" },
      ],
    },
    {
      id: "attachmentType",
      label: "첨부파일 분류",
      type: "text",
    },
    {
      id: "serialNo",
      label: "시리얼 번호",
      type: "text",
    },
    {
      id: "isVersionMatched",
      label: "버전 일치",
      type: "select",
      options: [
        { label: "일치", value: "true" },
        { label: "불일치", value: "false" },
      ],
    },
    {
      id: "hasMultipleRevisions",
      label: "다중 리비전",
      type: "select",
      options: [
        { label: "있음", value: "true" },
        { label: "없음", value: "false" },
      ],
    },
  ]

  if (data.length === 0) {
    return (
      <div className="border rounded-lg p-12 text-center">
        <div className="mx-auto mb-4 h-12 w-12 text-muted-foreground">
          📄
        </div>
        <p className="text-muted-foreground">응답할 첨부파일이 없습니다.</p>
      </div>
    )
  }

  return (
    // ✅ 상위 컨테이너 구조 단순화 및 너비 제한 해제
<>
      {/* 코멘트 범례 */}
      <div className="flex items-center gap-6 text-xs text-muted-foreground bg-muted/30 p-3 rounded-lg">
        <span className="font-medium">코멘트 범례:</span>
        <div className="flex items-center gap-1">
          <div className="w-2 h-2 rounded-full bg-blue-500"></div>
          <span>벤더 응답</span>
        </div>
        <div className="flex items-center gap-1">
          <div className="w-2 h-2 rounded-full bg-green-500"></div>
          <span>내부 메모</span>
        </div>
        <div className="flex items-center gap-1">
          <div className="w-2 h-2 rounded-full bg-red-500"></div>
          <span>수정 요청</span>
        </div>
        <div className="flex items-center gap-1">
          <div className="w-2 h-2 rounded-full bg-orange-500"></div>
          <span>발주처 리비전</span>
        </div>
      </div>
      <div style={{ 
        width: '100%', 
        maxWidth: '100%', 
        overflow: 'hidden',
        contain: 'layout'
      }}>
      {/* 데이터 테이블 - 컨테이너 제약 최소화 */}
      <ClientDataTable
        data={data}
        columns={columns}
        advancedFilterFields={advancedFilterFields}
               autoSizeColumns={true}
        compact={true}
        // ✅ RFQ 테이블에 맞는 컬럼 핀고정
        initialColumnPinning={{
          left: ["serialNo", "attachmentType"],
          right: ["actions"]
        }}
      >
             {showHeader && (
        <div className="flex items-center justify-between">
   
          {statistics && (
            <div className="flex items-center gap-4 text-sm text-muted-foreground">
              <span>전체 {statistics.total}개</span>
              <span className="text-green-600">최신 {statistics.upToDate}개</span>
              <span className="text-blue-600">업데이트필요 {statistics.versionMismatch}개</span>
              <span className="text-orange-600">미응답 {statistics.pending}개</span>
              {statistics.revisionRequested > 0 && (
                <span className="text-yellow-600">수정요청 {statistics.revisionRequested}개</span>
              )}
              {statistics.waived > 0 && (
                <span className="text-gray-600">포기 {statistics.waived}개</span>
              )}
            </div>
          )}
        </div>
      )}
        </ClientDataTable>
      </div>
      </>
  )
}
