import React, { useState, useEffect } from "react";
import PhoneInputScreen from "./PhoneInputScreen";
import OtpVerificationScreen from "./OtpVerificationScreen";
import UserProfileScreen from "./UserProfileScreen";

const AuthModal = ({ isOpen, onClose, user, setUser }) => {
  const [view, setView] = useState("phone");

  useEffect(() => {
    if (isOpen) {
      setView(user ? "profile" : "phone");
    }
  }, [isOpen, user]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm px-4">
      {/* Click outside to close */}
      <div className="absolute inset-0" onClick={onClose} />

      {/* Modal Container */}
      <div 
        className={`relative w-full shadow-2xl transition-all duration-300 ${
          view === "phone" ? "max-w-4xl bg-transparent" : "max-w-md bg-white rounded-2xl"
        }`}
      >
        {/* Close button X */}
        {(view === "otp" || view === "profile") && (
          <button 
            onClick={onClose}
            className="absolute top-4 right-4 z-10 text-gray-500 hover:text-dark-900 transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        )}
        
        {view === "phone" && (
          <div className="relative">
            <button 
              onClick={onClose}
              className="absolute top-4 right-4 z-10 text-gray-500 hover:text-dark-900 transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>
        )}

        {/* Content View Switching */}
        {view === "phone" && (
          <PhoneInputScreen 
            onRequestOtp={() => setView("otp")} 
            onCancel={onClose} 
            onGoogleSuccess={async (tokenResponse) => {
              try {
                const res = await fetch(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${tokenResponse.access_token}`);
                const data = await res.json();
                setUser(data);
                setView("profile");
              } catch (err) {
                alert("Failed to fetch Google profile.");
              }
            }}
            onRegisterSuccess={(formData) => {
              // Creating a mock user from the native registration form
              const newUser = {
                name: formData.name,
                email: formData.email,
                picture: `https://ui-avatars.com/api/?name=${formData.name.replace(' ', '+')}&background=random`,
                isNewRegistration: true
              };
              setUser(newUser);
              setView("profile");
            }}
          />
        )}
        
        {view === "otp" && (
          <OtpVerificationScreen 
            onBack={() => setView("phone")} 
            onSuccess={() => {
              // Create a dummy user for the OTP flow demo
              const fakeUser = { 
                name: "Customer", 
                email: "customer@phone.login", 
                picture: "https://ui-avatars.com/api/?name=Customer&background=random" 
              };
              setUser(fakeUser);
              setView("profile");
            }} 
          />
        )}

        {view === "profile" && (
          <UserProfileScreen 
            user={user} 
            onLogout={() => {
              setUser(null);
              onClose();
            }} 
          />
        )}
      </div>
    </div>
  );
};

export default AuthModal;
