"use client"
import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, Upload, Plus, Files, RefreshCw } from "lucide-react"
import { toast } from "sonner"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import {  SimplifiedDocumentsView } from "@/db/schema/vendorDocu"
import { SendToSHIButton } from "./send-to-shi-button"
import { ImportFromDOLCEButton } from "./import-from-dolce-button"

interface EnhancedDocTableToolbarActionsProps {
  table: Table<SimplifiedDocumentsView>
  projectType: "ship" | "plant"
  contractId?: number
}

export function EnhancedDocTableToolbarActions({
  table,
  projectType,
  contractId,
}: EnhancedDocTableToolbarActionsProps) {
  const [bulkUploadDialogOpen, setBulkUploadDialogOpen] = React.useState(false)
  
  // 현재 테이블의 모든 데이터 (필터링된 상태)
  const allDocuments = table.getFilteredRowModel().rows.map(row => row.original)
  
  // 모든 문서에서 고유한 contractId들 추출
  const contractIds = React.useMemo(() => {
    const ids = new Set(allDocuments.map(doc => doc.contractId))
    return Array.from(ids)
  }, [allDocuments])
  
  // 주요 contractId (가장 많은 문서가 속한 계약)
  const primaryContractId = React.useMemo(() => {
    if (contractId) return contractId
    if (contractIds.length === 0) return undefined
    
    const contractCounts = contractIds.map(id => ({
      id,
      count: allDocuments.filter(doc => doc.contractId === id).length
    }))
    
    return contractCounts.sort((a, b) => b.count - a.count)[0].id
  }, [contractId, contractIds, allDocuments])

  const handleSyncComplete = () => {
    // 동기화 완료 후 테이블 새로고침
    table.resetRowSelection()
    // 필요시 추가 액션 수행
  }

  const handleDocumentAdded = () => {
    // 테이블 새로고침
    table.resetRowSelection()
    
    // 추가적인 새로고침 시도
    setTimeout(() => {
      window.location.reload() // 강제 새로고침
    }, 500)
  }

  const handleImportComplete = () => {
    // 가져오기 완료 후 테이블 새로고침
    table.resetRowSelection()
    setTimeout(() => {
      window.location.reload()
    }, 500)
  }

  return (
    <div className="flex items-center gap-2">
    
        <>
          {/* SHIP: DOLCE에서 목록 가져오기 */}
          <ImportFromDOLCEButton
            allDocuments={allDocuments}
            onImportComplete={handleImportComplete}
          />
        </>
     

      {/* Export 버튼 (공통) */}
      <Button
        variant="outline"
        size="sm"
        onClick={() =>
          exportTableToExcel(table, {
            filename: "Document-list",
            excludeColumns: ["select", "actions"],
          })
        }
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Export</span>
      </Button>

      {/* Send to SHI 버튼 (공통) - 내부 → 외부로 보내기 */}
      {primaryContractId && (
        <SendToSHIButton
          contractId={primaryContractId}
          onSyncComplete={handleSyncComplete}
          projectType={projectType}
        />
      )}

   
    </div>
  )
}