import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Lock } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import tilloLogo from '../assets/Tillo.png';
import ritLogo from '../assets/RIT_Logo.webp';
import { auth, googleProvider } from '../firebase';
import { signInWithPopup } from 'firebase/auth';
import './LoginScreen.css';

const LoginScreen: React.FC = () => {
  const navigate = useNavigate();
  const { loginWithGoogle, checkEmailExists } = useAuth();

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSuspended, setIsSuspended] = useState(false);

  // First-time registration flow states
  const [showMobilePrompt, setShowMobilePrompt] = useState(false);
  const [pendingEmail, setPendingEmail] = useState('');
  const [pendingName, setPendingName] = useState('');
  const [mobileNumber, setMobileNumber] = useState('');

  const handleGoogleSignIn = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const result = await signInWithPopup(auth, googleProvider);
      const user = result.user;
      if (user.email) {
        // Check if user exists on backend
        const checkResult = await checkEmailExists(user.email);
        if (checkResult.exists) {
          // Already registered, log them in directly
          const backendResult = await loginWithGoogle(user.email, user.displayName || "Google User");
          if (backendResult.success) {
            navigate('/');
          } else if (backendResult.isSuspended) {
            setIsSuspended(true);
          } else {
            setError(backendResult.message);
          }
        } else {
          // First time sign-in, ask for mobile number
          setPendingEmail(user.email);
          setPendingName(user.displayName || "Google User");
          setShowMobilePrompt(true);
        }
      } else {
        setError('No email found in Google Account.');
      }
    } catch (err: any) {
      console.error(err);
      setError(err.message || 'Failed to authenticate with Google');
    } finally {
      setIsLoading(false);
    }
  };

  const handleMobileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!/^[0-9]{10}$/.test(mobileNumber)) {
      setError('Please enter a valid 10-digit mobile number');
      return;
    }

    setIsLoading(true);
    setError(null);
    try {
      const backendResult = await loginWithGoogle(pendingEmail, pendingName, mobileNumber);
      if (backendResult.success) {
        navigate('/');
      } else if (backendResult.isSuspended) {
        setIsSuspended(true);
      } else {
        setError(backendResult.message);
      }
    } catch (err: any) {
      setError(err.message || 'Registration failed');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container login-page">
      <div className="mesh-gradient-bg"></div>

      <div className="login-content">
        <div className="login-card animate-slideUp">
          <div className="login-header-logo flex flex-col items-center justify-center">
            <img src={tilloLogo} alt="Tillo Logo" className="tillo-logo" />
            <span className="login-tagline">Till yo tummy is full...</span>
          </div>

          <div className="login-header">
            <h1 className="login-title">
              {showMobilePrompt ? 'Almost Done!' : 'Welcome to Tillo'}
            </h1>
            <p className="login-subtitle">
              {showMobilePrompt ? 'Enter your mobile number to complete registration' : 'Sign in to your canteen account using Google Auth'}
            </p>
          </div>

          {error && <div className="error-message">{error}</div>}

          {showMobilePrompt ? (
            <form onSubmit={handleMobileSubmit} className="login-form">
              <div className="form-group">
                <label>Mobile Number</label>
                <div className="input-wrapper">
                  <input
                    type="tel"
                    placeholder="10-digit mobile number"
                    value={mobileNumber}
                    onChange={(e) => setMobileNumber(e.target.value.replace(/[^0-9]/g, '').slice(0, 10))}
                    disabled={isLoading}
                    style={{ paddingLeft: '16px' }}
                  />
                </div>
              </div>
              <button 
                type="submit" 
                className="login-button w-full"
                disabled={isLoading || mobileNumber.length !== 10}
              >
                {isLoading ? <div className="loading-dots"><span>.</span><span>.</span><span>.</span></div> : 'Register Account'}
              </button>
              <button 
                type="button" 
                className="back-to-mobile"
                onClick={() => { setShowMobilePrompt(false); setError(null); }}
                disabled={isLoading}
                style={{ background: 'none', border: 'none', cursor: 'pointer' }}
              >
                Cancel
              </button>
            </form>
          ) : (
            <div className="google-signin-wrapper">
              <button 
                className="google-login-btn" 
                onClick={handleGoogleSignIn} 
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="loading-dots">
                    <span>.</span><span>.</span><span>.</span>
                  </div>
                ) : (
                  <>
                    <svg className="google-icon" viewBox="0 0 24 24">
                      <path
                        fill="#4285F4"
                        d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                      />
                      <path
                        fill="#34A853"
                        d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                      />
                      <path
                        fill="#FBBC05"
                        d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
                      />
                      <path
                        fill="#EA4335"
                        d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                      />
                    </svg>
                    <span>Sign in with Google</span>
                  </>
                )}
              </button>
            </div>
          )}
        </div>

        <div className="login-merchant-card animate-slideUp">
          <div className="merchant-info">
            <span className="merchant-label">Merchant Partner</span>
          </div>
          <img src={ritLogo} alt="RIT Logo" className="merchant-rit-logo" />
        </div>

        <div className="login-footer-info">
          <p>© 2026 Rajalakshmi Institute of Technology</p>
          <p>Tillo Canteen Management System</p>
        </div>
      </div>

      {isSuspended && (
        <div className="suspension-overlay">
          <div className="suspension-modal animate-zoomIn">
            <div className="suspension-icon">
              <Lock size={40} />
            </div>
            <h2>Account Suspended</h2>
            <p>Your access to the Tillo Canteen system has been restricted by an administrator.</p>
            <div className="suspension-details">
              <span>Please contact the Admin or Manager to resolve this issue.</span>
            </div>
            <button className="suspension-close-btn" onClick={() => setIsSuspended(false)}>
              Back to Login
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default LoginScreen;
