"use client";

import React, { useRef, useEffect } from "react";
import { Button } from "@/components/ui/button";

interface ConfirmationPopoverProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  position?: "top" | "bottom";
  isLoading?: boolean;
}

const ConfirmationPopover: React.FC<ConfirmationPopoverProps> = ({
  isOpen,
  onClose,
  onConfirm,
  title,
  message,
  confirmText = "Confirm",
  cancelText = "Cancel",
  position = "top",
  isLoading = false,
}) => {
  const popoverRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        popoverRef.current &&
        !popoverRef.current.contains(event.target as Node)
      ) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div
      ref={popoverRef}
      className={`absolute z-50 bg-white rounded-md shadow-lg p-4 border border-gray-200 min-w-[200px]
  ${position === "top" ? "bottom-full mb-2" : "top-full mt-2"}
  right-0 max-h-[300px] overflow-y-auto`}
    >
      {title && <h3 className="font-medium text-sm mb-1">{title}</h3>}
      <p className="text-xs text-gray-600 mb-3">{message}</p>
      <div className="flex justify-end space-x-2">
        <Button
          variant="outline"
          size="sm"
          onClick={onClose}
          className="text-xs h-8 px-3"
        >
          {cancelText}
        </Button>
        <Button
          variant="destructive"
          size="sm"
          onClick={onConfirm}
          disabled={isLoading}
          className="text-xs h-8 px-3 bg-[#C10510] hover:bg-[#C10510]/90"
        >
          {confirmText}
        </Button>
      </div>
    </div>
  );
};

export default ConfirmationPopover;
