"use client"

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

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { EnhancedDocumentsView } from "@/db/schema/vendorDocu"
import { AddDocumentListDialog } from "./add-doc-dialog"
import { DeleteDocumentsDialog } from "./delete-docs-dialog"
import { BulkUploadDialog } from "./bulk-upload-dialog"
import type { EnhancedDocument } from "@/types/enhanced-documents"
import { SendToSHIButton } from "./send-to-shi-button"

interface EnhancedDocTableToolbarActionsProps {
  table: Table<EnhancedDocument>
  projectType: "ship" | "plant"
  selectedPackageId: number
  onNewDocument: () => void
  onBulkAction: (action: string, selectedRows: any[]) => Promise<void>
}

export function EnhancedDocTableToolbarActions({
  table,
  projectType,
  selectedPackageId,
  onNewDocument,
  onBulkAction
}: EnhancedDocTableToolbarActionsProps) {
  const [bulkUploadDialogOpen, setBulkUploadDialogOpen] = React.useState(false)
  
  // 현재 테이블의 모든 데이터 (필터링된 상태)
  const allDocuments = table.getFilteredRowModel().rows.map(row => row.original)

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

  return (
    <div className="flex items-center gap-2">
      {/* 기존 액션들 */}
      {table.getFilteredSelectedRowModel().rows.length > 0 ? (
        <DeleteDocumentsDialog
          documents={table
            .getFilteredSelectedRowModel()
            .rows.map((row) => row.original)}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}

      {/* 메인 액션 버튼들 */}
      {projectType === "plant" && (
        <Button onClick={onNewDocument} className="flex items-center gap-2">
          <Plus className="w-4 h-4" />
          새 문서
        </Button>
      )}
            
      {/* 일괄 업로드 버튼 */}
      <Button
        variant="outline"
        onClick={() => setBulkUploadDialogOpen(true)}
        className="flex items-center gap-2"
      >
        <Files className="w-4 h-4" />
        일괄 업로드
      </Button>

      {/* 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 버튼으로 교체 */}
      <SendToSHIButton
        contractId={selectedPackageId}
        documents={allDocuments}
        onSyncComplete={handleSyncComplete}
        projectType={projectType}
      />

      {/* 일괄 업로드 다이얼로그 */}
      <BulkUploadDialog
        open={bulkUploadDialogOpen}
        onOpenChange={setBulkUploadDialogOpen}
        documents={allDocuments}
        projectType={projectType}
        contractId={selectedPackageId}
      />
    </div>
  )
}