// simplified-documents-table.tsx
"use client"

import React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { getUserVendorDocuments, getUserVendorDocumentStats } from "@/lib/vendor-document-list/enhanced-document-service"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { toast } from "sonner"
import { Badge } from "@/components/ui/badge"
import { FileText } from "lucide-react"

import { Label } from "@/components/ui/label"
import { DataTable } from "@/components/data-table/data-table"
import { SimplifiedDocumentsView } from "@/db/schema"
import { getSimplifiedDocumentColumns } from "./enhanced-doc-table-columns"
import { EnhancedDocTableToolbarActions } from "./enhanced-doc-table-toolbar-actions"

// DrawingKind별 설명 매핑
const DRAWING_KIND_INFO = {
  B3: {
    title: "B3 Vendor",
    description: "Approval → Work 단계로 진행되는 승인 중심 도면",
    color: "bg-blue-50 text-blue-700 border-blue-200"
  },
  B4: {
    title: "B4 GTT", 
    description: "Pre → Work 단계로 진행되는 DOLCE 연동 도면",
    color: "bg-green-50 text-green-700 border-green-200"
  },
  B5: {
    title: "B5 FMEA",
    description: "First → Second 단계로 진행되는 순차적 도면", 
    color: "bg-purple-50 text-purple-700 border-purple-200"
  }
} as const

interface SimplifiedDocumentsTableProps {
  allPromises: Promise<[
    Awaited<ReturnType<typeof getUserVendorDocuments>>,
    Awaited<ReturnType<typeof getUserVendorDocumentStats>>
  ]>
  onDataLoaded?: (data: SimplifiedDocumentsView[]) => void
}

export function SimplifiedDocumentsTable({
  allPromises,
  onDataLoaded,
}: SimplifiedDocumentsTableProps) {
  // React.use()로 Promise 결과를 받고, 그 다음에 destructuring
  const [documentResult, statsResult] = React.use(allPromises)
  const { data, pageCount, total, drawingKind, vendorInfo } = documentResult
  const { stats, totalDocuments, primaryDrawingKind } = statsResult

  // 데이터가 로드되면 콜백 호출
  React.useEffect(() => {
    if (onDataLoaded && data) {
      onDataLoaded(data)
    }
  }, [data, onDataLoaded])

  // 기존 상태들
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<SimplifiedDocumentsView> | null>(null)
  const [expandedRows,] = React.useState<Set<string>>(new Set())

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

  // ✅ SimplifiedDocumentsView에 맞게 필터 필드 업데이트
  const advancedFilterFields: DataTableAdvancedFilterField<SimplifiedDocumentsView>[] = [
    {
      id: "docNumber",
      label: "문서번호",
      type: "text",
    },
    {
      id: "vendorDocNumber",
      label: "벤더 문서번호",
      type: "text",
    },
    {
      id: "title",
      label: "문서제목",
      type: "text",
    },
    {
      id: "drawingKind",
      label: "문서종류",
      type: "select",
      options: [
        { label: "B3", value: "B3" },
        { label: "B4", value: "B4" },
        { label: "B5", value: "B5" },
      ],
    },
    {
      id: "projectCode",
      label: "프로젝트 코드",
      type: "text",
    },
    {
      id: "vendorName",
      label: "벤더명",
      type: "text",
    },
    {
      id: "vendorCode",
      label: "벤더 코드",
      type: "text",
    },
    {
      id: "pic",
      label: "담당자",
      type: "text",
    },
    {
      id: "status",
      label: "문서 상태",
      type: "select",
      options: [
        { label: "활성", value: "ACTIVE" },
        { label: "비활성", value: "INACTIVE" },
        { label: "보류", value: "PENDING" },
        { label: "완료", value: "COMPLETED" },
      ],
    },
    {
      id: "firstStageName",
      label: "1차 스테이지",
      type: "text",
    },
    {
      id: "secondStageName",
      label: "2차 스테이지",
      type: "text",
    },
    {
      id: "firstStagePlanDate",
      label: "1차 계획일",
      type: "date",
    },
    {
      id: "firstStageActualDate",
      label: "1차 실제일",
      type: "date",
    },
    {
      id: "secondStagePlanDate",
      label: "2차 계획일",
      type: "date",
    },
    {
      id: "secondStageActualDate",
      label: "2차 실제일",
      type: "date",
    },
    {
      id: "issuedDate",
      label: "발행일",
      type: "date",
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      type: "date",
    },
  ]

  // ✅ B4 전용 필드들 (조건부로 추가)
  const b4FilterFields: DataTableAdvancedFilterField<SimplifiedDocumentsView>[] = [
    {
      id: "cGbn",
      label: "C 구분",
      type: "text",
    },
    {
      id: "dGbn",
      label: "D 구분",
      type: "text",
    },
    {
      id: "degreeGbn",
      label: "Degree 구분",
      type: "text",
    },
    {
      id: "deptGbn",
      label: "Dept 구분",
      type: "text",
    },
    {
      id: "jGbn",
      label: "J 구분",
      type: "text",
    },
    {
      id: "sGbn",
      label: "S 구분",
      type: "text",
    },
  ]

  // B4 문서가 있는지 확인하여 B4 전용 필드 추가
  const hasB4Documents = data.some(doc => doc.drawingKind === 'B4')
  const finalFilterFields = hasB4Documents
    ? [...advancedFilterFields, ...b4FilterFields]
    : advancedFilterFields

  const { table } = useDataTable({
    data: data,
    columns,
    pageCount,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.documentId),
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",
  })

  // 실제 데이터의 drawingKind 또는 주요 drawingKind 사용
  const activeDrawingKind = drawingKind || primaryDrawingKind
  const kindInfo = activeDrawingKind ? DRAWING_KIND_INFO[activeDrawingKind] : null

  return (
    <div className="w-full space-y-4">
      {/* DrawingKind 정보 간단 표시 */}
      {kindInfo && (
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="default" className="flex items-center gap-1 text-sm">
              <FileText className="w-4 h-4" />
              {kindInfo.title}
            </Badge>
            <span className="text-sm text-muted-foreground">
              {kindInfo.description}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="outline">
              {total}개 문서
            </Badge>
          </div>
        </div>
      )}

      {/* 테이블 */}
      <div className="overflow-x-auto">
        <DataTable table={table} compact>
          <DataTableAdvancedToolbar
            table={table}
            filterFields={finalFilterFields}
            shallow={false}
          >
              <EnhancedDocTableToolbarActions
                table={table}
                projectType="ship"
              />

          </DataTableAdvancedToolbar>
        </DataTable>
      </div>
    </div>
  )
}