"use client"

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

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Vendor } from "@/db/schema/vendors"
import { ApproveVendorsDialog } from "./approve-vendor-dialog"
import { RequestPQVendorsDialog } from "./request-vendor-pg-dialog"
import { RequestProjectPQDialog } from "./request-project-pq-dialog"
import { SendVendorsDialog } from "./send-vendor-dialog"
import { RequestVendorsInvestigateDialog } from "./request-vendor-investigate-dialog"
import { RequestInfoDialog } from "./request-additional-Info-dialog"

interface VendorsTableToolbarActionsProps {
  table: Table<Vendor>
}

export function VendorsTableToolbarActions({ table }: VendorsTableToolbarActionsProps) {
  // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식
  const fileInputRef = React.useRef<HTMLInputElement>(null)
  
  // 선택된 벤더 중 PENDING_REVIEW 상태인 벤더만 필터링
  const pendingReviewVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => vendor.status === "PENDING_REVIEW");
  }, [table.getFilteredSelectedRowModel().rows]);
  
  // 선택된 벤더 중 IN_REVIEW 상태인 벤더만 필터링
  const inReviewVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => vendor.status === "IN_REVIEW");
  }, [table.getFilteredSelectedRowModel().rows]);
  
  const approvedVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => vendor.status === "APPROVED");
  }, [table.getFilteredSelectedRowModel().rows]);
  
  const sendVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => vendor.status === "READY_TO_SEND");
  }, [table.getFilteredSelectedRowModel().rows]);
  
  const pqApprovedVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => vendor.status === "PQ_APPROVED");
  }, [table.getFilteredSelectedRowModel().rows]);
  
  // 프로젝트 PQ를 보낼 수 있는 벤더 상태 필터링
  const projectPQEligibleVendors = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
      .filter(vendor => 
        ["PENDING_REVIEW", "IN_REVIEW", "IN_PQ", "PQ_APPROVED", "APPROVED", "READY_TO_SEND", "ACTIVE"].includes(vendor.status)
      );
  }, [table.getFilteredSelectedRowModel().rows]);
  
  return (
    <div className="flex items-center gap-2">
      {/* 승인 다이얼로그: PENDING_REVIEW 상태인 벤더가 있을 때만 표시 */}
      {pendingReviewVendors.length > 0 && (
        <ApproveVendorsDialog
          vendors={pendingReviewVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {/* 일반 PQ 요청: IN_REVIEW 상태인 벤더가 있을 때만 표시 */}
      {inReviewVendors.length > 0 && (
        <RequestPQVendorsDialog
          vendors={inReviewVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {/* 프로젝트 PQ 요청: 적격 상태의 벤더가 있을 때만 표시 */}
      {projectPQEligibleVendors.length > 0 && (
        <RequestProjectPQDialog
          vendors={projectPQEligibleVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {approvedVendors.length > 0 && (
        <RequestInfoDialog
          vendors={approvedVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {sendVendors.length > 0 && (
        <RequestInfoDialog
          vendors={sendVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {pqApprovedVendors.length > 0 && (
        <RequestVendorsInvestigateDialog
          vendors={pqApprovedVendors}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      )}
      
      {/** 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>
    </div>
  )
}