"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download } from "lucide-react"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { BasicContractView } from "@/db/schema"
import { BasicContractSignDialog } from "./basic-contract-sign-dialog"

interface TemplateTableToolbarActionsProps {
  table: Table<BasicContractView>
}

export function BasicContractTableToolbarActions({ table }: TemplateTableToolbarActionsProps) {
  const params = useParams()
  const lng = (params?.lng as string) || "ko"
  const { t, ready } = useTranslation(lng, "procurement")

  // 안전한 번역 함수
  const safeT = React.useCallback((key: string, fallback: string) => {
    if (!ready) return fallback;
    const translated = t(key);
    return translated === key ? fallback : translated;
  }, [t, ready]);

  // PENDING 상태인 선택된 계약서들
  const pendingContracts = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(contract => contract.status === "PENDING");
  }, [table.getFilteredSelectedRowModel().rows]);

  // 선택된 행이 있는지 확인
  const hasSelectedRows = table.getFilteredSelectedRowModel().rows.length > 0;

  return (
    <div className="flex items-center gap-2">
      {/* 서명 버튼 - 항상 표시하되 내부에서 조건 체크 */}
      <BasicContractSignDialog
        contracts={pendingContracts}
        onSuccess={() => table.toggleAllRowsSelected(false)}
        hasSelectedRows={hasSelectedRows}
        t={safeT}
      />

      {/* Export 버튼 */}
      <Button
        variant="outline"
        size="sm"
        onClick={() =>
          exportTableToExcel(table, {
            filename: "basic-contract-requested-list",
            excludeColumns: ["select", "actions"],
          })
        }
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">
          {safeT("basicContracts.toolbar.export", lng === 'ko' ? "내보내기" : "Export")}
        </span>
      </Button>
    </div>
  )
}