
"use client";

import * as React from "react";
import { Lock, LockOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { toast } from "sonner";
import { toggleRfqSealed } from "../service";

interface RfqSealToggleCellProps {
  rfqId: number;
  isSealed: boolean;
  onUpdate?: () => void;
}

export function RfqSealToggleCell({ 
  rfqId, 
  isSealed, 
  onUpdate 
}: RfqSealToggleCellProps) {
  const [isLoading, setIsLoading] = React.useState(false);
  const [currentSealed, setCurrentSealed] = React.useState(isSealed);

  const handleToggle = async (e: React.MouseEvent) => {
    e.stopPropagation(); // 행 선택 방지
    
    setIsLoading(true);
    try {
      const result = await toggleRfqSealed(rfqId);
      
      if (result.success) {
        setCurrentSealed(result.data?.rfqSealedYn ?? !currentSealed);
        toast.success(result.message);
        onUpdate?.(); // 테이블 데이터 새로고침
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      toast.error("밀봉 상태 변경 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0"
            onClick={handleToggle}
            disabled={isLoading}
          >
            {currentSealed ? (
              <Lock className="h-4 w-4 text-red-500" />
            ) : (
              <LockOpen className="h-4 w-4 text-gray-400" />
            )}
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <p>{currentSealed ? "밀봉 해제하기" : "밀봉하기"}</p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}

export const sealColumn = {
    accessorKey: "rfqSealedYn",
    header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="견적 밀봉" />,
    cell: ({ row, table }) => (
      <RfqSealToggleCell
        rfqId={row.original.id}
        isSealed={row.original.rfqSealedYn}
        onUpdate={() => {
          // 테이블 데이터를 새로고침하는 로직
          // 이 부분은 상위 컴포넌트에서 refreshData 함수를 prop으로 전달받아 사용
          const meta = table.options.meta as any;
          meta?.refreshData?.();
        }}
      />
    ),
    size: 80,
  };