// enhanced-documents-table-with-drawing-filter.tsx
"use client"

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

import { useDataTable } from "@/hooks/use-data-table"
import { StageRevisionExpandedContent } from "./stage-revision-expanded-content"
import { RevisionUploadDialog } from "./revision-upload-dialog"
import { EnhancedDocTableToolbarActions } from "./enhanced-doc-table-toolbar-actions"
import { getEnhancedDocuments } from "../enhanced-document-service"
import type { EnhancedDocument } from "@/types/enhanced-documents"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { 
  AlertTriangle, 
  Clock, 
  TrendingUp, 
  Target, 
  Users,
  Settings,
  Filter
} from "lucide-react"
import { useTranslation } from "@/i18n/client"
import { useParams } from "next/navigation"
import { getUpdatedEnhancedColumns } from "./enhanced-doc-table-columns"
import { ExpandableDataTable } from "@/components/data-table/expandable-data-table"
import { toast } from "sonner"
import { UpdateDocumentSheet } from "./update-doc-sheet"
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Label } from "@/components/ui/label"

interface FinalIntegratedDocumentsTableProps {
  promises: Promise<[Awaited<ReturnType<typeof getEnhancedDocuments>>]>
  selectedPackageId: number
  projectType: "ship" | "plant"
  contractId: number
  initialDrawingKind?: string
}

// ✅ Drawing Kind 옵션 정의
const DRAWING_KIND_KEYS = [
  { value: "all", label: "전체 문서" },
  { value: "B3", label: "B3: Vendor" },
  { value: "B4", label: "B4: GTT" },
  { value: "B5", label: "B5: FMEA" },
] as const

export function EnhancedDocumentsTable({
  promises,
  selectedPackageId,
  projectType,
  contractId,
  initialDrawingKind = "all"
}: FinalIntegratedDocumentsTableProps) {
  const [{ data, pageCount, total }] = React.use(promises)
  
  // URL에서 언어 파라미터 가져오기
  const params = useParams()
  const lng = (params?.lng as string) || 'ko'
  const { t } = useTranslation(lng, 'engineering')
  console.log(t, 't')

  // ✅ Drawing Kind 옵션 동적 생성
  const DRAWING_KIND_OPTIONS = React.useMemo(() => 
    DRAWING_KIND_KEYS.map(item => ({
      value: item.value,
      label: t(`documentList.drawingKindOptions.${item.value}`)
    }))
  , [t])

  // ✅ Drawing Kind 필터 상태 추가
  const [drawingKindFilter, setDrawingKindFilter] = React.useState<string>(initialDrawingKind)
  
  // 기존 상태들
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<EnhancedDocument> | null>(null)
  const [expandedRows, setExpandedRows] = React.useState<Set<string>>(new Set())
  const [quickFilter, setQuickFilter] = React.useState<'all' | 'overdue' | 'due_soon' | 'in_progress' | 'high_priority'>('all')
  const [expandedStages, setExpandedStages] = React.useState<Record<string, Record<number, boolean>>>({})
  const [uploadDialogOpen, setUploadDialogOpen] = React.useState(false)
  const [editSheetOpen, setEditSheetOpen] = React.useState(false)
  const [selectedDocument, setSelectedDocument] = React.useState<EnhancedDocument | null>(null)
  const [selectedStage, setSelectedStage] = React.useState<string>("")
  const [selectedRevision, setSelectedRevision] = React.useState<string>("")
  const [uploadMode, setUploadMode] = React.useState<'new' | 'append'>('new')

  // ✅ Drawing Kind별 데이터 필터링
  const filteredByDrawingKind = React.useMemo(() => {
    if (drawingKindFilter === "all") return data
    return data.filter(doc => doc.drawingKind === drawingKindFilter)
  }, [data, drawingKindFilter])

  // ✅ Drawing Kind별 통계 계산
  const drawingKindStats = React.useMemo(() => {
    const stats = DRAWING_KIND_OPTIONS.reduce((acc, option) => {
      if (option.value === "all") {
        acc[option.value] = data.length
      } else {
        acc[option.value] = data.filter(doc => doc.drawingKind === option.value).length
      }
      return acc
    }, {} as Record<string, number>)
    
    return stats
  }, [data])

  // 다음 리비전 계산 함수
  const getNextRevision = React.useCallback((currentRevision: string): string => {
    if (!currentRevision) return "A"
    
    if (/^[A-Z]$/.test(currentRevision)) {
      const charCode = currentRevision.charCodeAt(0)
      if (charCode < 90) {
        return String.fromCharCode(charCode + 1)
      }
      return "AA"
    }
    
    if (/^\d+$/.test(currentRevision)) {
      return String(parseInt(currentRevision) + 1)
    }
    
    return currentRevision
  }, [])

  // ✅ 컬럼 정의 - drawingKindFilter 추가
  const columns = React.useMemo(
    () => getUpdatedEnhancedColumns({ 
      setRowAction: (action) => {
        setRowAction(action)
        if (action) {
          setSelectedDocument(action.row.original)
          
          switch (action.type) {
            case "update":
              setEditSheetOpen(true)
              break
            case "upload":
              setSelectedStage(action.row.original.currentStageName || "")
              setUploadDialogOpen(true)
              break
            case "view":
              const rowId = action.row.id
              const newExpanded = new Set(expandedRows)
              if (newExpanded.has(rowId)) {
                newExpanded.delete(rowId)
              } else {
                newExpanded.add(rowId)
              }
              setExpandedRows(newExpanded)
              break
          }
        }
      },
      projectType,
      drawingKindFilter // ✅ 추가
    }),
    [expandedRows, projectType, drawingKindFilter]
  )

  // 기존 통계 계산
  const stats = React.useMemo(() => {
    const totalDocs = filteredByDrawingKind.length
    const overdue = filteredByDrawingKind.filter(doc => doc.isOverdue).length
    const dueSoon = filteredByDrawingKind.filter(doc => 
      doc.daysUntilDue !== null && 
      doc.daysUntilDue >= 0 && 
      doc.daysUntilDue <= 3
    ).length
    const inProgress = filteredByDrawingKind.filter(doc => doc.currentStageStatus === 'IN_PROGRESS').length
    const highPriority = filteredByDrawingKind.filter(doc => doc.currentStagePriority === 'HIGH').length
    const avgProgress = totalDocs > 0 
      ? Math.round(filteredByDrawingKind.reduce((sum, doc) => sum + (doc.progressPercentage || 0), 0) / totalDocs)
      : 0
    
    return { 
      total: totalDocs, 
      overdue, 
      dueSoon, 
      inProgress, 
      highPriority, 
      avgProgress 
    }
  }, [filteredByDrawingKind])

  // 빠른 필터링
  const filteredData = React.useMemo(() => {
    switch (quickFilter) {
      case 'overdue':
        return filteredByDrawingKind.filter(doc => doc.isOverdue)
      case 'due_soon':
        return filteredByDrawingKind.filter(doc => 
          doc.daysUntilDue !== null && 
          doc.daysUntilDue >= 0 && 
          doc.daysUntilDue <= 3
        )
      case 'in_progress':
        return filteredByDrawingKind.filter(doc => doc.currentStageStatus === 'IN_PROGRESS')
      case 'high_priority':
        return filteredByDrawingKind.filter(doc => doc.currentStagePriority === 'HIGH')
      default:
        return filteredByDrawingKind
    }
  }, [filteredByDrawingKind, quickFilter])

  // 나머지 핸들러 함수들
  const handleUploadRevision = React.useCallback((document: EnhancedDocument, stageName?: string, currentRevision?: string, mode: 'new' | 'append' = 'new') => {
    setSelectedDocument(document)
    setSelectedStage(stageName || document.currentStageName || "")
    setUploadMode(mode)
    
    if (mode === 'new') {
      if (currentRevision) {
        const nextRevision = getNextRevision(currentRevision)
        setSelectedRevision(nextRevision)
      } else {
        const latestRevision = findLatestRevisionInStage(document, stageName || document.currentStageName || "")
        if (latestRevision) {
          setSelectedRevision(getNextRevision(latestRevision))
        } else {
          setSelectedRevision("A")
        }
      }
    } else {
      setSelectedRevision(currentRevision || "")
    }
    
    setUploadDialogOpen(true)
  }, [getNextRevision])

  const findLatestRevisionInStage = React.useCallback((document: EnhancedDocument, stageName: string) => {
    const stage = document.allStages?.find(s => s.stageName === stageName)
    if (!stage || !stage.revisions || stage.revisions.length === 0) {
      return null
    }
    
    const sortedRevisions = [...stage.revisions].sort((a, b) => {
      const aIsAlpha = /^[A-Z]+$/.test(a.revision)
      const bIsAlpha = /^[A-Z]+$/.test(b.revision)
      
      if (aIsAlpha && bIsAlpha) {
        return a.revision.localeCompare(b.revision)
      } else if (!aIsAlpha && !bIsAlpha) {
        return parseInt(a.revision) - parseInt(b.revision)
      } else {
        return aIsAlpha ? -1 : 1
      }
    })
    
    return sortedRevisions[sortedRevisions.length - 1]?.revision || null
  }, [])

  const handleNewDocument = () => {
    // AddDocumentListDialog는 자체적으로 Dialog trigger를 가지므로 별도 처리 불필요
  }

  const handleStageToggle = React.useCallback((documentId: string, stageId: number) => {
    setExpandedStages(prev => ({
      ...prev,
      [documentId]: {
        ...prev[documentId],
        [stageId]: !prev[documentId]?.[stageId]
      }
    }))
  }, [])

  const handleBulkAction = async (action: string, selectedRows: any[]) => {
    try {
      if (action === 'bulk_approve') {
        const stageIds = selectedRows
          .map(row => row.original.currentStageId)
          .filter(Boolean)
        
        if (stageIds.length > 0) {
          toast.success(t('documentList.messages.approvalSuccess', { count: stageIds.length }))
        }
      } else if (action === 'bulk_upload') {
        toast.info(t('documentList.messages.bulkUploadPending'))
      }
    } catch (error) {
      toast.error(t('documentList.messages.bulkActionError'))
    }
  }

  const closeAllDialogs = () => {
    setUploadDialogOpen(false)
    setEditSheetOpen(false)
    setSelectedDocument(null)
    setSelectedStage("")
    setSelectedRevision("")
    setUploadMode('new')
    setRowAction(null)
  }

  const convertToUpdateFormat = React.useCallback((doc: EnhancedDocument | null) => {
    if (!doc) return null
    
    return {
      id: doc.documentId,
      contractId: contractId,
      docNumber: doc.docNumber,
      title: doc.title,
      status: doc.status || "pending",
      description: doc.description || null,
      remarks: doc.remarks || null,
    }
  }, [contractId])

  // 필터 필드 정의
  const filterFields: DataTableFilterField<EnhancedDocument>[] = [
    {
      label: "문서번호",
      value: "docNumber",
      placeholder: "문서번호로 검색...",
    },
    {
      label: "제목",
      value: "title", 
      placeholder: "제목으로 검색...",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<EnhancedDocument>[] = [
    {
      id: "docNumber",
      label: t('documentList.filters.documentNumber'),
      type: "text",
    },
    {
      id: "title",
      label: t('documentList.filters.documentTitle'),
      type: "text",
    },
    {
      id: "drawingKind",
      label: t('documentList.filters.documentType'),
      type: "select",
      options: [
        { label: "B3", value: "B3" },
        { label: "B4", value: "B4" },
        { label: "B5", value: "B5" },
      ],
    },
    {
      id: "currentStageStatus",
      label: t('documentList.filters.stageStatus'),
      type: "select",
      options: [
        { label: t('documentList.statusOptions.planned'), value: "PLANNED" },
        { label: t('documentList.statusOptions.inProgress'), value: "IN_PROGRESS" },
        { label: t('documentList.statusOptions.submitted'), value: "SUBMITTED" },
        { label: t('documentList.statusOptions.approved'), value: "APPROVED" },
        { label: t('documentList.statusOptions.completed'), value: "COMPLETED" },
      ],
    },
    {
      id: "currentStagePriority",
      label: t('documentList.filters.priority'),
      type: "select",
      options: [
        { label: t('documentList.priorityOptions.high'), value: "HIGH" },
        { label: t('documentList.priorityOptions.medium'), value: "MEDIUM" },
        { label: t('documentList.priorityOptions.low'), value: "LOW" },
      ],
    },
    {
      id: "isOverdue",
      label: t('documentList.filters.overdueStatus'),
      type: "select",
      options: [
        { label: t('documentList.overdueOptions.overdue'), value: "true" },
        { label: t('documentList.overdueOptions.normal'), value: "false" },
      ],
    },
    {
      id: "currentStageAssigneeName",
      label: t('documentList.filters.assignee'),
      type: "text",
    },
    {
      id: "createdAt",
      label: t('documentList.filters.createdDate'),
      type: "date",
    },
  ]

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

  return (
    <div className="space-y-6">


      {/* 통계 대시보드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('all')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {drawingKindFilter === "all" ? t('documentList.dashboard.totalDocuments') : `${DRAWING_KIND_OPTIONS.find(o => o.value === drawingKindFilter)?.label}`}
            </CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">
              {t('documentList.dashboard.totalCount', { total, shown: stats.total })}
            </p>
          </CardContent>
        </Card>
        
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('overdue')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('documentList.dashboard.overdueDocuments')}</CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.overdue}</div>
            <p className="text-xs text-muted-foreground">{t('documentList.dashboard.checkImmediately')}</p>
          </CardContent>
        </Card>
        
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('due_soon')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('documentList.dashboard.dueSoonDocuments')}</CardTitle>
            <Clock className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">{stats.dueSoon}</div>
            <p className="text-xs text-muted-foreground">{t('documentList.dashboard.dueInDays')}</p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('documentList.dashboard.averageProgress')}</CardTitle>
            <Target className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.avgProgress}%</div>
            <p className="text-xs text-muted-foreground">{t('documentList.dashboard.overallProgress')}</p>
          </CardContent>
        </Card>
      </div>

      {/* 빠른 필터 + 문서 종류 필터 */}
      <div className="flex flex-col sm:flex-row gap-4 justify-between items-start sm:items-center">
        {/* 왼쪽: 빠른 필터 */}
        <div className="flex gap-2 overflow-x-auto pb-2">
          <Badge 
            variant={quickFilter === 'all' ? 'default' : 'outline'}
            className="cursor-pointer hover:bg-primary hover:text-primary-foreground whitespace-nowrap"
            onClick={() => setQuickFilter('all')}
          >
            {t('documentList.quickFilters.all')} ({stats.total})
          </Badge>
          <Badge 
            variant={quickFilter === 'overdue' ? 'destructive' : 'outline'}
            className="cursor-pointer hover:bg-destructive hover:text-destructive-foreground whitespace-nowrap"
            onClick={() => setQuickFilter('overdue')}
          >
            <AlertTriangle className="w-3 h-3 mr-1" />
            {t('documentList.quickFilters.overdue')} ({stats.overdue})
          </Badge>
          <Badge 
            variant={quickFilter === 'due_soon' ? 'default' : 'outline'}
            className="cursor-pointer hover:bg-orange-500 hover:text-white whitespace-nowrap"
            onClick={() => setQuickFilter('due_soon')}
          >
            <Clock className="w-3 h-3 mr-1" />
            {t('documentList.quickFilters.dueSoon')} ({stats.dueSoon})
          </Badge>
          <Badge 
            variant={quickFilter === 'in_progress' ? 'default' : 'outline'}
            className="cursor-pointer hover:bg-blue-500 hover:text-white whitespace-nowrap"
            onClick={() => setQuickFilter('in_progress')}
          >
            <Users className="w-3 h-3 mr-1" />
            {t('documentList.quickFilters.inProgress')} ({stats.inProgress})
          </Badge>
          <Badge 
            variant={quickFilter === 'high_priority' ? 'destructive' : 'outline'}
            className="cursor-pointer hover:bg-destructive hover:text-destructive-foreground whitespace-nowrap"
            onClick={() => setQuickFilter('high_priority')}
          >
            <Target className="w-3 h-3 mr-1" />
            {t('documentList.quickFilters.highPriority')} ({stats.highPriority})
          </Badge>
        </div>

        {/* 오른쪽: 문서 종류 필터 */}
        <div className="flex items-center gap-2 flex-shrink-0">
          <Select value={drawingKindFilter} onValueChange={setDrawingKindFilter}>
            <SelectTrigger className="w-[140px]">
              <SelectValue placeholder={t('documentList.filters.selectDocumentType')} />
            </SelectTrigger>
            <SelectContent>
              {DRAWING_KIND_OPTIONS.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  <div className="flex items-center justify-between w-full">
                    <span>{option.label}</span>
                    <Badge variant="outline" className="ml-2 text-xs">
                      {drawingKindStats[option.value] || 0}
                    </Badge>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          
          {/* B4 필드 표시 안내 (아이콘만) */}
          {drawingKindFilter === "B4" && (
            <div className="flex items-center gap-1 text-blue-600 bg-blue-50 px-2 py-1 rounded text-xs">
              <Settings className="h-3 w-3" />
              <span className="hidden sm:inline">{t('documentList.ui.expandedInfoAvailable')}</span>
            </div>
          )}
        </div>
      </div>

      {/* 메인 테이블 */}
      <div className="space-y-4">
        <div className="rounded-md border bg-white overflow-hidden">
          <ExpandableDataTable 
            table={table}
            expandable={true}
            expandedRows={expandedRows}
            setExpandedRows={setExpandedRows}
            renderExpandedContent={(document) => (
              <div className="">
                <StageRevisionExpandedContent 
                  document={document}
                  onUploadRevision={handleUploadRevision}
                  projectType={projectType}
                  expandedStages={expandedStages[String(document.documentId)] || {}}
                  onStageToggle={(stageId) => handleStageToggle(String(document.documentId), stageId)}
                  // showB4Fields={document.drawingKind === "B4"}
                />
              </div>
            )}
            expandedRowClassName="!p-0"
            excludeFromClick={[
              'actions',      
              'select'        
            ]}
          >
            <DataTableAdvancedToolbar
              table={table}
              filterFields={advancedFilterFields}
              shallow={false}
            >
              <EnhancedDocTableToolbarActions
                table={table}
                projectType={projectType}
                selectedPackageId={selectedPackageId}
                contractId={contractId}
                onNewDocument={handleNewDocument}
                onBulkAction={handleBulkAction}
              />
            </DataTableAdvancedToolbar>
          </ExpandableDataTable>
        </div>
      </div>

      {/* 다이얼로그들 */}
      <RevisionUploadDialog
        open={uploadDialogOpen}
        onOpenChange={(open) => {
          if (!open) closeAllDialogs()
          else setUploadDialogOpen(open)
        }}
        document={selectedDocument}
        projectType={projectType}
        presetStage={selectedStage}
        presetRevision={selectedRevision}
        mode={uploadMode}
      />

      <UpdateDocumentSheet
        open={editSheetOpen}
        onOpenChange={(open) => {
          if (!open) closeAllDialogs()
          else setEditSheetOpen(open)
        }}
        document={convertToUpdateFormat(selectedDocument)}
      />
    </div>
  )
}