"use client"

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

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { VendorInvestigationsViewWithContacts } from "@/config/vendorInvestigationsColumnsConfig"
import { InvestigationCancelPlanButton } from "./investigation-cancel-plan-button"
import { ChangeQMManagerDialog } from "./change-qm-manager-dialog"


interface VendorsTableToolbarActionsProps {
  table: Table<VendorInvestigationsViewWithContacts>
}

export function VendorsTableToolbarActions({ table }: VendorsTableToolbarActionsProps) {
  // 선택된 행 분석
  const selectedRows = table.getFilteredSelectedRowModel().rows
  const selectedData = selectedRows.map(row => row.original)

  // QM 담당자 변경 가능 여부 체크 (선택된 항목이 1개이고 상태가 PLANNED)
  const canChangeQM = selectedData.length === 1 && selectedData[0].investigationStatus === "PLANNED"
  const selectedInvestigation = canChangeQM ? selectedData[0] : null

  // QM 담당자 변경 다이얼로그 상태
  const [showChangeQMDialog, setShowChangeQMDialog] = React.useState(false)

  const handleChangeQMClick = () => {
    if (canChangeQM) {
      setShowChangeQMDialog(true)
    }
  }

  const handleChangeQMSuccess = () => {
    // 테이블 선택 초기화
    table.toggleAllPageRowsSelected(false)
    setShowChangeQMDialog(false)
  }

  return (
    <div className="flex items-center gap-2">
      <InvestigationCancelPlanButton table={table} />

      {/* QM 담당자 변경 버튼 - 계획 상태이고 단일 선택일 때만 활성화 */}
      {canChangeQM && (
        <Button
          variant="outline"
          size="sm"
          onClick={handleChangeQMClick}
          className="gap-2"
        >
          <UserCog className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">QM 담당자 변경</span>
        </Button>
      )}

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

      {/* QM 담당자 변경 다이얼로그 */}
      {selectedInvestigation && (
        <ChangeQMManagerDialog
          isOpen={showChangeQMDialog}
          onClose={() => setShowChangeQMDialog(false)}
          investigationId={selectedInvestigation.investigationId}
          currentQMManagerId={selectedInvestigation.qmManagerId}
          currentQMManagerName={selectedInvestigation.qmManagerName}
          onSuccess={handleChangeQMSuccess}
        />
      )}
    </div>
  )
}