"use client"

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

import { Button } from "@/components/ui/button"
import { type ApprovalTemplate } from "@/lib/approval-template/service"
import { toast } from "sonner"
import { DeleteApprovalTemplateDialog } from "./delete-approval-template-dialog"
import { CategoryManagementDialog } from "./category-management-dialog"

interface ApprovalTemplateTableToolbarActionsProps {
  table: Table<ApprovalTemplate>
  onCreateTemplate: () => void
}

export function ApprovalTemplateTableToolbarActions({
  table,
  onCreateTemplate,
}: ApprovalTemplateTableToolbarActionsProps) {
  const [showDeleteDialog, setShowDeleteDialog] = React.useState(false)
  const [showCategoryDialog, setShowCategoryDialog] = React.useState(false)

  const selectedRows = table.getFilteredSelectedRowModel().rows
  const selectedTemplates = selectedRows.map((row) => row.original)

  return (
    <div className="flex items-center gap-2">
      {/* 카테고리 관리 버튼 */}
      <CategoryManagementDialog
        open={showCategoryDialog}
        onOpenChange={setShowCategoryDialog}
        showTrigger={false}
      />

      {/* 새 템플릿 버튼 */}
      <Button variant="outline" size="sm" onClick={() => setShowCategoryDialog(true)}>
        카테고리 관리
      </Button>

      {/* 새 템플릿 버튼 */}
      <Button variant="default" size="sm" onClick={onCreateTemplate}>
        <Plus className="mr-2 size-4" aria-hidden="true" />
        새 템플릿
      </Button>

      {/* 일괄 삭제 */}
      {selectedTemplates.length > 0 && (
        <>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowDeleteDialog(true)}
            className="text-destructive hover:text-destructive"
          >
            <Trash className="mr-2 size-4" aria-hidden="true" />
            삭제 ({selectedTemplates.length})
          </Button>

          <DeleteApprovalTemplateDialog
            open={showDeleteDialog}
            onOpenChange={setShowDeleteDialog}
            templates={selectedTemplates}
            showTrigger={false}
            onSuccess={() => {
              table.toggleAllRowsSelected(false)
              setShowDeleteDialog(false)
            }}
          />
        </>
      )}
    </div>
  )
}
