"use client"

import * as React from "react"
import { type Task } from "@/db/schema/tasks"
import { type Table } from "@tanstack/react-table"
import { Download, Upload } from "lucide-react"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { DeleteTemplatesDialog } from "./delete-basicContract-dialog"
import { AddTemplateDialog } from "./add-basic-contract-template-dialog"
import { DisposeDocumentsDialog } from "./dispose-documents-dialog"
import { BasicContractTemplate } from "@/db/schema"

interface TemplateTableToolbarActionsProps {
  table: Table<BasicContractTemplate>
}

export function TemplateTableToolbarActions({ table }: TemplateTableToolbarActionsProps) {
  // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식
  const selectedRows = table.getFilteredSelectedRowModel().rows
  const selectedDocuments = selectedRows.map((row) => row.original)
  
  // 선택된 문서들의 상태 확인
  const hasActiveDocuments = selectedDocuments.some(doc => doc.status === 'ACTIVE')
  const hasDisposedDocuments = selectedDocuments.some(doc => doc.status === 'DISPOSED')

  return (
    <div className="flex items-center gap-2">
      {/** 1) 선택된 로우가 있으면 삭제 다이얼로그 */}
      {selectedRows.length > 0 ? (
        <DeleteTemplatesDialog
          templates={selectedDocuments}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}

      {/** 2) 선택된 활성 문서가 있으면 폐기 다이얼로그 */}
      {selectedRows.length > 0 && hasActiveDocuments ? (
        <DisposeDocumentsDialog
          open={false}
          onOpenChange={() => {}}
          documents={selectedDocuments.filter(doc => doc.status === 'ACTIVE')}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}

      {/** 3) 선택된 폐기 문서가 있으면 복구 다이얼로그 */}
      {selectedRows.length > 0 && hasDisposedDocuments ? (
        <DisposeDocumentsDialog
          open={false}
          onOpenChange={() => {}}
          documents={selectedDocuments.filter(doc => doc.status === 'DISPOSED')}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}

      <AddTemplateDialog/>

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