import React, { useState, useEffect } from "react";
import { ShoppingCart } from "lucide-react";

interface LoadingModalProps {
  isOpen: boolean;
  title: string;
  message: string;
}

const LoadingModal: React.FC<LoadingModalProps> = ({
  isOpen,
  title,
  message,
}) => {
  const [isAnimating, setIsAnimating] = useState(false);
  const [shouldRender, setShouldRender] = useState(false);

  console.log("🔄 [LOADING_MODAL] Renderizando - isOpen:", isOpen);

  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
      // Pequeno delay para garantir que o DOM está pronto antes de iniciar a animação
      setTimeout(() => setIsAnimating(true), 10);
    } else {
      // Iniciar animação de saída
      setIsAnimating(false);
      // Remover do DOM após a animação terminar
      const timer = setTimeout(() => setShouldRender(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  // Não renderizar se não deve estar visível
  if (!shouldRender) {
    console.log("🔄 [LOADING_MODAL] Modal não está aberto, retornando null");
    return null;
  }

  console.log("🔄 [LOADING_MODAL] Renderizando modal com título:", title);

  return (
    <div className="fixed inset-0 z-[200] flex items-center justify-center">
      {/* Overlay */}
      <div
        className={`absolute inset-0 bg-[#001f3f]/60 backdrop-blur-sm transition-opacity duration-300 ${
          isAnimating ? "opacity-100" : "opacity-0"
        }`}
      ></div>

      {/* Dialog */}
      <div
        className={`relative bg-white rounded-3xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 ${
          isAnimating ? "scale-100 opacity-100" : "scale-95 opacity-0"
        }`}
      >
        {/* Header */}
        <div className="p-6 bg-[#002147] text-white rounded-t-3xl relative overflow-hidden">
          <div className="relative z-10">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-12 h-12 bg-blue-500/20 rounded-2xl flex items-center justify-center">
                <ShoppingCart className="w-6 h-6 text-orange-400" />
              </div>
              <div className="flex-1">
                <h3 className="text-xl font-black">{title}</h3>
                <p className="text-xs text-blue-400 font-bold uppercase tracking-wider mt-0.5">
                  Carregando
                </p>
              </div>
            </div>
          </div>
          <div className="absolute right-[-10%] top-[-10%] w-32 h-32 bg-blue-400/10 rounded-full blur-2xl"></div>
        </div>

        {/* Content */}
        <div className="p-6">
          <div className="flex items-center gap-4">
            <div className="w-8 h-8 border-4 border-[#002147] border-t-transparent rounded-full animate-spin flex-shrink-0"></div>
            <p className="text-slate-600 text-sm leading-relaxed">{message}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoadingModal;
