/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { UserAccount, UserRole } from '../types';
import { 
  Lock, 
  Mail, 
  User, 
  KeyRound, 
  CheckCircle, 
  Building2, 
  ShieldAlert, 
  Sparkles, 
  ArrowRight, 
  Inbox,
  ExternalLink,
  Info
} from 'lucide-react';

interface AuthScreensProps {
  onAuthSuccess: (user: UserAccount) => void;
}

export default function AuthScreens({ onAuthSuccess }: AuthScreensProps) {
  // Modes: 'login' | 'register' | 'owner-login' | 'owner-register' | 'admin-login' | 'verify'
  const [mode, setMode] = useState<'login' | 'register' | 'owner-login' | 'owner-register' | 'admin-login' | 'verify'>('login');
  
  // Fields
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [adminPass, setAdminPass] = useState('');
  
  // Verification
  const [verificationCodeInput, setVerificationCodeInput] = useState('');
  const [pendingUser, setPendingUser] = useState<UserAccount | null>(null);
  
  // Alerts / Simulated inbox
  const [error, setError] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [showSimulatedInbox, setShowSimulatedInbox] = useState(false);

  // Helper: Retrieve all registered accounts from state or localStorage
  const getStoredUsers = (): UserAccount[] => {
    const data = localStorage.getItem('charge_park_users');
    if (!data) {
      // Default sample accounts
      const defaults: UserAccount[] = [
        {
          id: 'cust-demo-1',
          email: 'user@gmail.com',
          name: 'Rohan Sharma',
          role: 'customer',
          isEmailVerified: true,
          createdAt: new Date().toISOString(),
          phone: '+91 98765 43210',
          vehicleNo: 'MH12-FB-8899',
          vehicleModel: 'Tata Nexon EV Max',
          walletBalance: 250, // ₹250 welcome credit
          completedCheckins: 1,
          nextDiscountPercent: 5 // Starter 5% discount
        },
        {
          id: 'owner-demo-1',
          email: 'owner@gmail.com',
          name: 'Nitin Gadkari Properties',
          role: 'owner',
          isEmailVerified: true,
          createdAt: new Date().toISOString()
        }
      ];
      localStorage.setItem('charge_park_users', JSON.stringify(defaults));
      return defaults;
    }
    return JSON.parse(data);
  };

  const saveStoredUser = (user: UserAccount) => {
    const list = getStoredUsers().filter(u => u.email !== user.email);
    list.push(user);
    localStorage.setItem('charge_park_users', JSON.stringify(list));
  };

  // 1. Customer/Owner Registration Init
  const handleRegister = async (e: React.FormEvent, registeredRole: UserRole) => {
    e.preventDefault();
    setError('');
    setSuccessMsg('');

    if (!name.trim() || !email.trim() || !password.trim()) {
      setError('Please provide name, email, and security password.');
      return;
    }

    if (!/\S+@\S+\.\S+/.test(email)) {
      setError('Please enter a valid email address.');
      return;
    }

    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, password, role: registeredRole })
      });
      const data = await res.json();
      
      if (!res.ok) {
        setError(data.error || 'Registration failed.');
        return;
      }

      setPendingUser(data.user);
      saveStoredUser(data.user);
      setMode('verify');
      setShowSimulatedInbox(true);
      setSuccessMsg(`Simulated registration complete! Verification PIN code sent.`);
    } catch (err) {
      setError('Failed to contact database on server. Retrying...');
    }
  };

  // 2. Customer/Owner Login
  const handleLogin = async (e: React.FormEvent, attemptedRole: UserRole) => {
    e.preventDefault();
    setError('');
    setSuccessMsg('');

    if (!email.trim() || !password.trim()) {
      setError('Please enter your email address and password.');
      return;
    }

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, role: attemptedRole })
      });
      const data = await res.json();
      
      if (!res.ok) {
        setError(data.error || 'Login failed.');
        return;
      }

      const user = data.user;

      // Check email verification status
      if (!user.isEmailVerified) {
        setPendingUser(user);
        setMode('verify');
        setShowSimulatedInbox(true);
        setError('Your email is registered but not verified yet. View mailbox below.');
        return;
      }

      // Success login
      onAuthSuccess(user);
    } catch (err) {
      setError('Credentials check failed due to database connectivity. Retry.');
    }
  };

  // 3. Email verification link or input submit
  const handleVerifySubmit = async (e?: React.FormEvent, forceVerifyCode?: string) => {
    if (e) e.preventDefault();
    setError('');

    if (!pendingUser) {
      setError('No verification flow detected. Try registering first.');
      return;
    }

    const submittedCode = forceVerifyCode || verificationCodeInput.trim();

    try {
      const res = await fetch('/api/auth/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: pendingUser.email, code: submittedCode })
      });
      const data = await res.json();
      
      if (!res.ok) {
        setError(data.error || 'Invalid 6-digit confirmation pin code.');
        return;
      }

      const verifiedUser = data.user;
      saveStoredUser(verifiedUser);
      setPendingUser(null);
      setVerificationCodeInput('');
      setShowSimulatedInbox(false);
      
      // Complete login redirects to index
      onAuthSuccess(verifiedUser);
    } catch (err) {
      setError('Verification service timeout. Try again.');
    }
  };

  // 4. Admin Access authentication (via special developer bypass)
  const handleAdminAuth = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    try {
      const res = await fetch('/api/auth/admin-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ passcode: adminPass })
      });
      const data = await res.json();
      
      if (!res.ok) {
        setError(data.error || 'Security access check failed.');
        return;
      }

      onAuthSuccess(data.user);
    } catch (err) {
      setError('Could not establish admin handshake with Firestore root.');
    }
  };

  return (
    <div className="min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 py-12 relative overflow-hidden text-slate-100 font-sans select-none">
      
      {/* Background radial overlays */}
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,_var(--tw-gradient-stops))] from-amber-500/10 via-slate-900 to-slate-950 pointer-events-none z-0" />
      <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-amber-500/5 rounded-full blur-3xl pointer-events-none" />
      <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-emerald-500/5 rounded-full blur-3xl pointer-events-none" />

      {/* Main Container */}
      <div className="w-full max-w-md z-10 space-y-6">
        
        {/* Brand Header */}
        <div className="text-center select-none space-y-2">
          <div className="inline-flex items-center gap-1.5 p-3 rounded-2xl bg-amber-500/20 text-amber-500 border border-amber-500/30 font-black text-xl mb-2 hover:scale-105 transition-all">
            <span>P</span>
            <span className="w-1.5 h-5 bg-amber-500 rounded-sm rotate-12 inline-block"></span>
            <span className="font-sans font-black tracking-tighter text-slate-100">ChargeBuddy</span>
          </div>
          <h2 className="text-2xl font-black text-white tracking-tight">EV Reservoirs & Parking</h2>
          <p className="text-slate-400 text-xs max-w-sm mx-auto">Compare local fees, locate active charging plugins & reserve your slot instantly across Bihar districts.</p>
        </div>

        {/* Auth selector Tabs */}
        <div className="grid grid-cols-3 gap-1 bg-slate-950 p-1.5 rounded-xl border border-slate-800">
          <button
            onClick={() => { setMode('login'); setError(''); }}
            className={`py-2 text-[11px] font-extrabold rounded-lg transition-all
              ${(mode === 'login' || mode === 'register' || mode === 'verify') 
                ? 'bg-amber-500 text-slate-950 shadow-md font-black' 
                : 'text-slate-400 hover:text-slate-200'}`}
          >
            Driver App
          </button>
          
          <button
            onClick={() => { setMode('owner-login'); setError(''); }}
            className={`py-2 text-[11px] font-extrabold rounded-lg transition-all
              ${(mode === 'owner-login' || mode === 'owner-register') 
                ? 'bg-emerald-600 text-white shadow-md font-black animate-pulse-subtle' 
                : 'text-slate-400 hover:text-slate-200'}`}
          >
            Property Owner
          </button>

          <button
            onClick={() => { setMode('admin-login'); setError(''); }}
            className={`py-2 text-[11px] font-extrabold rounded-lg transition-all
              ${mode === 'admin-login' 
                ? 'bg-sky-600 text-white shadow-md font-black' 
                : 'text-slate-400 hover:text-slate-200'}`}
          >
            App Admin
          </button>
        </div>

        {/* Mode Form Content */}
        <div className="bg-slate-950/80 backdrop-blur-md border border-slate-800/80 p-6 rounded-2xl shadow-xl space-y-4">
          
          {/* Form Header info */}
          <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
            {mode === 'login' && <h3 className="font-bold text-white text-base">Vehicle Owner Login</h3>}
            {mode === 'register' && <h3 className="font-bold text-white text-base">Create Free Driver Account</h3>}
            {mode === 'owner-login' && <h3 className="font-bold text-emerald-400 text-base flex items-center gap-1.5"><Building2 className="w-4 h-4" /> Owner Gateway</h3>}
            {mode === 'owner-register' && <h3 className="font-bold text-emerald-400 text-base flex items-center gap-1.5"><Building2 className="w-4 h-4" /> Register New Hub Provider</h3>}
            {mode === 'admin-login' && <h3 className="font-bold text-sky-400 text-base flex items-center gap-1.5"><KeyRound className="w-4 h-4" /> Root Administrator Bypass</h3>}
            {mode === 'verify' && <h3 className="font-bold text-amber-400 text-base flex items-center gap-1.5"><Inbox className="w-4 h-4" /> Verify Verification Pin</h3>}
          </div>

          {/* Feedback alerts */}
          {error && (
            <div className="p-3 bg-rose-950/60 border border-rose-800/80 text-rose-300 text-xs rounded-xl font-medium">
              {error}
            </div>
          )}

          {successMsg && (
            <div className="p-3 bg-emerald-950/60 border border-emerald-800/80 text-emerald-300 text-xs rounded-xl font-medium">
              {successMsg}
            </div>
          )}

          {/* Render Actual Forms */}
          {mode === 'login' && (
            <form onSubmit={(e) => handleLogin(e, 'customer')} className="space-y-4">
              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">Email Address</label>
                <div className="relative">
                  <Mail className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="email"
                    placeholder="user@gmail.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-amber-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">Password</label>
                <div className="relative">
                  <Lock className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-amber-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-1 text-sm mt-2"
              >
                <span>Access Dashboard</span>
                <ArrowRight className="w-4 h-4" />
              </button>

              <div className="text-center text-xs text-slate-500 pt-1">
                <span>First time calling here? </span>
                <button
                  type="button"
                  onClick={() => { setMode('register'); setError(''); }}
                  className="text-amber-500 font-bold hover:underline"
                >
                  Create Driver Account
                </button>
              </div>
            </form>
          )}

          {mode === 'register' && (
            <form onSubmit={(e) => handleRegister(e, 'customer')} className="space-y-4">
              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">Your Full Name</label>
                <div className="relative">
                  <User className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="text"
                    placeholder="Rohan Sharma"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-amber-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">Email Address</label>
                <div className="relative">
                  <Mail className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="email"
                    placeholder="driver@gmail.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-amber-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-slate-400 tracking-wider">Choose Safe Password</label>
                <div className="relative">
                  <Lock className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-amber-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-1.5 text-sm mt-2"
              >
                <span>Register & Verify Email</span>
                <Sparkles className="w-4 h-4 text-slate-950 fill-slate-950" />
              </button>

              <div className="text-center text-xs text-slate-500 pt-1">
                <span>Already have a pilot profile? </span>
                <button
                  type="button"
                  onClick={() => { setMode('login'); setError(''); }}
                  className="text-amber-500 font-bold hover:underline"
                >
                  Log In Here
                </button>
              </div>
            </form>
          )}

          {mode === 'owner-login' && (
            <form onSubmit={(e) => handleLogin(e, 'owner')} className="space-y-4">
              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-emerald-400 tracking-wider">Hub Owner Email</label>
                <div className="relative">
                  <Mail className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="email"
                    placeholder="owner@domain.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-emerald-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-emerald-400 tracking-wider">Password</label>
                <div className="relative">
                  <Lock className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-emerald-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-1.5 text-sm mt-3"
              >
                <span>Partner Dashboard Login</span>
                <Building2 className="w-4 h-4" />
              </button>

              <div className="text-center text-xs text-slate-500 pt-1">
                <span>Want to list your parking place/charger? </span>
                <button
                  type="button"
                  onClick={() => { setMode('owner-register'); setError(''); }}
                  className="text-emerald-400 font-bold hover:underline"
                >
                  Sign Up as Partner
                </button>
              </div>
            </form>
          )}

          {mode === 'owner-register' && (
            <form onSubmit={(e) => handleRegister(e, 'owner')} className="space-y-4">
              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-emerald-400 tracking-wider">Company / Partner Name</label>
                <div className="relative">
                  <User className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="text"
                    placeholder="e.g. Bihar EV Chargers Corp"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-emerald-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-emerald-400 tracking-wider">Business Email Address</label>
                <div className="relative">
                  <Mail className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="email"
                    placeholder="provider@chargepark.in"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-emerald-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="block text-[10px] uppercase font-bold text-emerald-400 tracking-wider">Set Secure Access Pass</label>
                <div className="relative">
                  <Lock className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-emerald-500 outline-none text-slate-100 text-sm"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-1.5 text-sm mt-3"
              >
                <span>Partner Registration</span>
                <CheckCircle className="w-4 h-4" />
              </button>

              <div className="text-center text-xs text-slate-500 pt-1">
                <span>Already registered provider? </span>
                <button
                  type="button"
                  onClick={() => { setMode('owner-login'); setError(''); }}
                  className="text-emerald-400 font-bold hover:underline"
                >
                  Log In Here
                </button>
              </div>
            </form>
          )}

          {mode === 'admin-login' && (
            <form onSubmit={handleAdminAuth} className="space-y-4">
              <div className="p-3 bg-sky-950/40 border border-sky-800/40 rounded-xl text-[11px] text-slate-300 flex items-start gap-2 select-none">
                <Info className="w-4 h-4 shrink-0 text-sky-400" />
                <span>Enter the global developer master passcode bypass link parameter to access terminal analytics and listing confirmations over Bihar.</span>
              </div>

              <div className="space-y-1.5">
                <div className="flex justify-between items-center">
                  <label className="block text-[10px] uppercase font-bold text-sky-400 tracking-wider">Master Key Pass</label>
                </div>
                <div className="relative">
                  <Lock className="absolute top-3 left-3 w-4 h-4 text-slate-500" />
                  <input
                    type="password"
                    placeholder="Enter master passcode"
                    value={adminPass}
                    onChange={(e) => setAdminPass(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl focus:border-sky-500 outline-none text-slate-100 text-sm placeholder-slate-600"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-sky-600 hover:bg-sky-500 text-white font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-2 text-sm"
              >
                <KeyRound className="w-4 h-4" />
                <span>Verify Master Authority</span>
              </button>
            </form>
          )}

          {mode === 'verify' && pendingUser && (
            <div className="space-y-5">
              <div className="text-center space-y-1">
                <p className="text-xs text-slate-400">A security check-in registration link has been broadcasted to</p>
                <p className="text-sm font-black text-amber-400">{pendingUser.email}</p>
              </div>

              <form onSubmit={(e) => handleVerifySubmit(e)} className="space-y-4">
                <div className="space-y-1.5 text-center">
                  <label className="block text-[11px] font-bold text-slate-400 uppercase tracking-widest">Enter 6-Digit Code</label>
                  <input
                    type="text"
                    maxLength={6}
                    placeholder="e.g. 524091"
                    value={verificationCodeInput}
                    onChange={(e) => setVerificationCodeInput(e.target.value.replace(/[^0-9]/g, ''))}
                    className="w-36 text-center py-2.5 tracking-widest text-lg font-mono font-black bg-slate-900 border-2 border-slate-800 hover:border-amber-500/50 rounded-xl text-slate-100 outline-none focus:border-amber-500"
                    required
                  />
                </div>

                <div className="flex gap-2.5">
                  <button
                    type="button"
                    onClick={() => { setMode('login'); setPendingUser(null); }}
                    className="flex-1 py-2 text-xs bg-slate-900 border border-slate-800 text-slate-400 font-bold rounded-lg"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="flex-1 py-2 text-xs bg-amber-500 text-slate-950 font-bold rounded-lg hover:bg-amber-400"
                  >
                    Verify Code
                  </button>
                </div>
              </form>
            </div>
          )}

        </div>

        {/* Info Credentials Helper Box */}
        <div className="p-4 bg-slate-950/60 border border-slate-800/80 rounded-2xl text-slate-400 text-xs text-center select-none space-y-1.5">
          <div className="font-bold text-slate-300 flex items-center justify-center gap-1 text-[11px] uppercase tracking-wider">
            <ShieldAlert className="w-3.5 h-3.5 text-amber-500" />
            <span>Simulated Sandbox Logins</span>
          </div>
          <div className="grid grid-cols-2 gap-2 text-[10px] text-left">
            <div className="bg-slate-900 p-1.5 rounded border border-slate-800/50">
              <span className="text-amber-500 font-bold block">🚨 Driver Acc:</span>
              <span>user@gmail.com</span><br/>
              <span>pass: <span className="font-mono">123456</span></span>
            </div>
            <div className="bg-slate-900 p-1.5 rounded border border-slate-800/50">
              <span className="text-emerald-400 font-bold block">🏨 Hub Owner Acc:</span>
              <span>owner@gmail.com</span><br/>
              <span>pass: <span className="font-mono">123456</span></span>
            </div>
          </div>
          <div className="text-[9px] text-slate-500 pt-1">
            Create any new driver or hub business account to automatically simulate the verification email inbox!
          </div>
        </div>

      </div>
    </div>
  );
}
