import { IconButton } from "@mui/material";
import { MdClose } from "react-icons/md";
import { useEffect, useState } from "react";
import TaleButton from "./TaleButton";
import { TaleCircularProgress } from "./TaleCircularProgress";

export const TaleAreYouSure = ({ 
  title, 
  text, 
  onConfirm, 
  onCancel, 
  confirmText = "Confirm", // Added prop to support custom text from parent
  cancelText = "Cancel",  // Added prop
  isLoading: externalLoading // Added to sync with parent loading state
}) => {
  const [internalLoading, setInternalLoading] = useState(false);
  const loading = externalLoading || internalLoading;

  useEffect(() => {
    const initialScroll = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = initialScroll;
    };
  }, []);

  return (
    /* Wrapper to center and create the backdrop */
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
      
      {/* The Modal Box */}
      <div
        style={{ boxShadow: "0 10px 25px rgba(0, 0, 0, 0.2)" }}
        className="w-full max-w-md rounded-2xl p-6 flex flex-col items-stretch gap-5 bg-white animate-in fade-in zoom-in duration-200"
      >
        {/* Row 1: Title and Close Button */}
        <div className="flex items-center justify-between">
          <span className="font-bold text-lg text-gray-800">{title}</span>
          <IconButton onClick={onCancel} size="small">
            <MdClose />
          </IconButton>
        </div>

        {/* Row 2: Text */}
        <div className="text-gray-700 leading-relaxed">
          {text}
        </div>

        {/* Row 3: Cancel and Confirm Buttons */}
        <div className="flex justify-end gap-3 mt-2">
          <TaleButton 
            directParentClassName="!text-sm !p-2" 
            role="business" 
            onClick={onCancel}
            disabled={loading}
          >
            {cancelText}
          </TaleButton>
          <TaleButton
            role="business"
            onClick={async () => {
              if (loading) return;
              setInternalLoading(true);
              await onConfirm();
              setInternalLoading(false);
            }}
            className="!text-sm min-w-[120px]"
            variant="outlined"
          >
            {loading ? <TaleCircularProgress colorOverride="white" size={20} /> : confirmText}
          </TaleButton>
        </div>
      </div>
    </div>
  );
};
