"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { 
  Download, 
  Upload, 
  Settings2, 
  ArrowUpDown, 
  Edit, 
  Eye,
  FileText,
  Wand2
} from "lucide-react"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { CreateGtcClauseDialog } from "./create-gtc-clause-dialog"
import { PreviewDocumentDialog } from "./preview-document-dialog"
import { DeleteGtcClausesDialog } from "./delete-gtc-clauses-dialog"

interface GtcClausesTableToolbarActionsProps {
  table: Table<GtcClauseTreeView>
  documentId: number
  document: any
}

export function GtcClausesTableToolbarActions({
  table,
  documentId,
  document,
}: GtcClausesTableToolbarActionsProps) {
  const [showCreateDialog, setShowCreateDialog] = React.useState(false)
  const [showReorderDialog, setShowReorderDialog] = React.useState(false)
  const [showBulkUpdateDialog, setShowBulkUpdateDialog] = React.useState(false)
  const [showGenerateVariablesDialog, setShowGenerateVariablesDialog] = React.useState(false)
  const [showPreviewDialog, setShowPreviewDialog] = React.useState(false) // ✅ 미리보기 다이얼로그 상태

  const selectedRows = table.getSelectedRowModel().rows
  const selectedCount = selectedRows.length
  
  // ✅ 테이블의 모든 데이터 가져오기
  const allClauses = table.getRowModel().rows.map(row => row.original)

  const handleExportToExcel = () => {
    // Excel 내보내기 로직
    console.log("Export to Excel")
  }

  const handleImportFromExcel = () => {
    // Excel 가져오기 로직
    console.log("Import from Excel")
  }

  const handlePreviewDocument = () => {
    // ✅ 미리보기 다이얼로그 열기
    setShowPreviewDialog(true)
  }

  const handleGenerateDocument = () => {
    // 최종 문서 생성
    console.log("Generate final document")
  }

  const handleReorderClauses = () => {
    setShowReorderDialog(true)
  }

  const handleBulkUpdate = () => {
    setShowBulkUpdateDialog(true)
  }

  const handleGenerateVariables = () => {
    setShowGenerateVariablesDialog(true)
  }

  const handleRefreshTable = () => {
    // 테이블 새로고침 로직
    console.log("Refresh table after creation")
    // table.reset() 또는 상위 컴포넌트의 refetch 함수 호출
  }

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 조항 추가 버튼 */}
        <CreateGtcClauseDialog
          documentId={documentId}
          document={document}
          onSuccess={handleRefreshTable}
        />

        {/* 선택된 항목이 있을 때 표시되는 액션들 */}
        {selectedCount > 0 && (
          <>
            <DeleteGtcClausesDialog
                gtcClauses={allClauses}
          onSuccess={() => table.toggleAllRowsSelected(false)}

            />
          </>
        )}

        {/* 관리 도구 드롭다운 */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm">
              <Settings2 className="mr-2 h-4 w-4" />
              관리 도구
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-56">
            {/* <DropdownMenuItem onClick={handleReorderClauses}>
              <ArrowUpDown className="mr-2 h-4 w-4" />
              조항 순서 변경
            </DropdownMenuItem>
            
            <DropdownMenuItem onClick={handleGenerateVariables}>
              <Wand2 className="mr-2 h-4 w-4" />
              PDFTron 변수명 일괄 생성
            </DropdownMenuItem> */}

            <DropdownMenuSeparator />
            
            <DropdownMenuItem onClick={handleExportToExcel}>
              <Download className="mr-2 h-4 w-4" />
              Excel로 내보내기
            </DropdownMenuItem>
            
            <DropdownMenuItem onClick={handleImportFromExcel}>
              <Upload className="mr-2 h-4 w-4" />
              Excel에서 가져오기
            </DropdownMenuItem>

            <DropdownMenuSeparator />
            
            <DropdownMenuItem onClick={handlePreviewDocument}>
              <Eye className="mr-2 h-4 w-4" />
              문서 미리보기
            </DropdownMenuItem>
            
            {/* <DropdownMenuItem onClick={handleGenerateDocument}>
              <FileText className="mr-2 h-4 w-4" />
              최종 문서 생성
            </DropdownMenuItem> */}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* 조건부로 표시되는 다이얼로그들 */}
        {showReorderDialog && (
          <div>
            {/* ReorderGtcClausesDialog 컴포넌트가 여기에 올 예정 */}
          </div>
        )}

        {showBulkUpdateDialog && (
          <div>
            {/* BulkUpdateGtcClausesDialog 컴포넌트가 여기에 올 예정 */}
          </div>
        )}

        {showGenerateVariablesDialog && (
          <div>
            {/* GenerateVariableNamesDialog 컴포넌트가 여기에 올 예정 */}
          </div>
        )}
      </div>

      {/* ✅ 미리보기 다이얼로그 */}
      <PreviewDocumentDialog
        open={showPreviewDialog}
        onOpenChange={setShowPreviewDialog}
        clauses={allClauses}
        document={document}
        onExport={() => {
          console.log("Export from preview dialog")
        }}
      />
    </>
  )
}