"use client";

import * as React from "react";
import { Table } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { Users, RefreshCw, FileDown, Plus } from "lucide-react";
import { RfqsLastView } from "@/db/schema";
import { RfqAssignPicDialog } from "./rfq-assign-pic-dialog";
import { Badge } from "@/components/ui/badge";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface RfqTableToolbarActionsProps<TData> {
  table: Table<TData>;
  rfqCategory?: "general" | "itb" | "rfq";
  onRefresh?: () => void;
}

export function RfqTableToolbarActions<TData>({ 
  table, 
  rfqCategory = "itb",
  onRefresh 
}: RfqTableToolbarActionsProps<TData>) {
  const [showAssignDialog, setShowAssignDialog] = React.useState(false);
  
  // 선택된 행 가져오기
  const selectedRows = table.getFilteredSelectedRowModel().rows;
  
  // 선택된 RFQ의 ID와 코드 추출
  const selectedRfqData = React.useMemo(() => {
    const rows = selectedRows.map(row => row.original as RfqsLastView);
    return {
      ids: rows.map(row => row.id),
      codes: rows.map(row => row.rfqCode || ""),
      // "I"로 시작하는 ITB만 필터링
      itbCount: rows.filter(row => row.rfqCode?.startsWith("I")).length,
      totalCount: rows.length
    };
  }, [selectedRows]);

  // 담당자 지정 가능 여부 체크 ("I"로 시작하는 항목이 있는지)
  const canAssignPic = selectedRfqData.itbCount > 0;

  const handleAssignSuccess = () => {
    // 테이블 선택 초기화
    table.toggleAllPageRowsSelected(false);
    // 데이터 새로고침
    onRefresh?.();
  };

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 담당자 지정 버튼 - 선택된 항목 중 ITB가 있을 때만 표시 */}
        {selectedRfqData.totalCount > 0 && canAssignPic && (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="default"
                  size="sm"
                  onClick={() => setShowAssignDialog(true)}
                  className="flex items-center gap-2"
                >
                  <Users className="h-4 w-4" />
                  담당자 지정
                  <Badge variant="secondary" className="ml-1">
                    {selectedRfqData.itbCount}건
                  </Badge>
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>선택한 ITB에 구매 담당자를 지정합니다</p>
                {selectedRfqData.itbCount !== selectedRfqData.totalCount && (
                  <p className="text-xs text-muted-foreground mt-1">
                    전체 {selectedRfqData.totalCount}건 중 ITB {selectedRfqData.itbCount}건만 지정됩니다
                  </p>
                )}
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        )}

        {/* 선택된 항목 표시 */}
        {selectedRfqData.totalCount > 0 && (
          <div className="flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md">
            <span className="text-sm text-muted-foreground">
              선택된 항목:
            </span>
            <Badge variant="secondary">
              {selectedRfqData.totalCount}건
            </Badge>
            {selectedRfqData.totalCount !== selectedRfqData.itbCount && (
              <Badge variant="outline" className="text-xs">
                ITB {selectedRfqData.itbCount}건
              </Badge>
            )}
          </div>
        )}

        {/* 기존 버튼들 */}
        <Button
          variant="outline"
          size="sm"
          onClick={onRefresh}
          className="flex items-center gap-2"
        >
          <RefreshCw className="h-4 w-4" />
          새로고침
        </Button>

        {rfqCategory === "general" && (
          <Button
            variant="outline"
            size="sm"
            className="flex items-center gap-2"
          >
            <Plus className="h-4 w-4" />
            일반견적 생성
          </Button>
        )}

        <Button
          variant="outline"
          size="sm"
          className="flex items-center gap-2"
          disabled={selectedRfqData.totalCount === 0}
        >
          <FileDown className="h-4 w-4" />
          엑셀 다운로드
        </Button>
      </div>

      {/* 담당자 지정 다이얼로그 */}
      <RfqAssignPicDialog
        open={showAssignDialog}
        onOpenChange={setShowAssignDialog}
        selectedRfqIds={selectedRfqData.ids}
        selectedRfqCodes={selectedRfqData.codes}
        onSuccess={handleAssignSuccess}
      />
    </>
  );
}