'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Eye, EyeOff, ArrowRight, Loader2, CheckCircle2, AlertCircle, Mail, Lock, User, ShieldCheck } from 'lucide-react';
import { CountryCodeDropdown } from '@/components/ui/CountryCodeDropdown';
import TurnstileWidget from '@/components/ui/TurnstileWidget';
import { getApiPath } from '@/lib/basePath';
import { useGoogleLogin } from '@react-oauth/google';

// Google icon SVG
function GoogleIcon() {
  return (
    <svg className="w-4 h-4" 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>
  );
}

async function readJsonSafely(response) {
  const text = await response.text();
  if (!text) return {};

  try {
    return JSON.parse(text);
  } catch {
    if (response.ok) {
      throw new Error('Unexpected response from the server.');
    }
    return {};
  }
}

function getCurrentTrackingSource() {
  if (typeof window === 'undefined') {
    return { page: '/tools/signin', path: '/tools/signin' };
  }

  const pathname = String(window.location.pathname || '/tools/signin') || '/tools/signin';
  const search = String(window.location.search || '');
  const href = String(window.location.href || '');
  const fallbackSource = {
    page: pathname,
    path: `${pathname}${search}`,
    pageUrl: href || `${pathname}${search}`,
  };

  try {
    const url = new URL(href);
    const getParam = (name) => String(url.searchParams.get(name) || '').trim();
    return {
      ...fallbackSource,
      pageUrl: url.toString(),
      utm_source: getParam('utm_source'),
      utm_medium: getParam('utm_medium'),
      utm_campaign: getParam('utm_campaign'),
      utm_term: getParam('utm_term'),
      utm_content: getParam('utm_content'),
      gclid: getParam('gclid'),
      fbclid: getParam('fbclid'),
      msclkid: getParam('msclkid'),
    };
  } catch {
    return fallbackSource;
  }
}

export default function InlineAuthForm({ onSuccess, defaultMode = 'signin', onSignUp, freeTrial = false, allowRegister = true }) {
  const [mode, setMode] = useState(!allowRegister && defaultMode === 'register' ? 'signin' : defaultMode); // 'signin' | 'register' | 'otp' | 'forgot' | 'forgot_sent'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [countryCode, setCountryCode] = useState('+91');
  const [otp, setOtp] = useState('');
  const [otpPurpose, setOtpPurpose] = useState('email-verification');
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [otpNotice, setOtpNotice] = useState('');
  const [forgotMessage, setForgotMessage] = useState('');
  const [googleLoading, setGoogleLoading] = useState(false);
  const [turnstileToken, setTurnstileToken] = useState('');
  const [turnstileResetKey, setTurnstileResetKey] = useState(0);

  const clearError = () => {
    setError('');
    setOtpNotice('');
  };

  const handleSignIn = async (e) => {
    e.preventDefault();
    setLoading(true);
    clearError();
    try {
      const res = await fetch(getApiPath('/api/auth/login'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          password,
          ...(freeTrial ? { freeTrial: true } : {}),
          source: getCurrentTrackingSource(),
        }),
      });
      const data = await readJsonSafely(res);
      if (data?.requiresTwoFactor) {
        setEmail(data.email || email.trim());
        setOtpPurpose('login');
        setMode('otp');
        setOtp('');
        setOtpNotice(data.message || 'Enter the verification code sent to your email.');
        return;
      }
      if (!res.ok) {
        if (data?.requiresEmailVerification) {
          setOtpPurpose('email-verification');
          setMode('otp');
          setOtp('');
          setOtpNotice(data.message || 'Please verify your email with the 6-digit code.');
          return;
        }
        throw new Error(data.message || 'Login failed');
      }

      // Update AuthContext if possible, or just call onSuccess
      onSuccess(data.user);
    } catch (err) {
      setError(err?.message || 'Invalid email or password. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    clearError();
    if (!turnstileToken) {
      setError('Complete the security verification before creating your account.');
      return;
    }
    setLoading(true);
    try {
      const normalizedPhone = phone.trim();
      const phoneWithCode = normalizedPhone.startsWith('+')
        ? normalizedPhone
        : `${countryCode} ${normalizedPhone}`;
      const res = await fetch(getApiPath('/api/auth/register'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          firstName: firstName.trim(),
          lastName: lastName.trim(),
          phone: phoneWithCode,
          email,
          password,
          turnstileToken,
          ...(freeTrial ? { freeTrial: true } : {}),
          source: getCurrentTrackingSource(),
        }),
      });
      const data = await readJsonSafely(res);
      if (!res.ok) {
        setTurnstileToken('');
        setTurnstileResetKey((value) => value + 1);
        throw new Error(data.message || 'Could not create account. Please try again.');
      }
      if (data?.requiresEmailVerification) {
        setOtpPurpose('email-verification');
        setMode('otp');
        setOtp('');
        setOtpNotice(data.message || 'We sent a verification code to your email.');
        return;
      }
      onSuccess(data.user);
    } catch (err) {
      setError(err?.message || 'Could not create account. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async (e) => {
    e.preventDefault();
    setLoading(true);
    clearError();
    try {
      const res = await fetch(getApiPath(
        otpPurpose === 'login' ? '/api/auth/verify-login-otp' : '/api/auth/verify-otp'
      ), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), otp: otp.trim(), source: getCurrentTrackingSource() }),
      });
      const data = await readJsonSafely(res);
      if (!res.ok) throw new Error(data.message || 'Invalid or expired code. Please try again.');
      onSuccess(data.user);
    } catch (err) {
      setError(err?.message || 'Invalid or expired code. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleResendOtp = async () => {
    clearError();
    try {
      const res = await fetch(getApiPath(
        otpPurpose === 'login' ? '/api/auth/request-login-otp' : '/api/auth/resend-otp'
      ), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      const data = await readJsonSafely(res);
      if (!res.ok) throw new Error(data.message || 'Could not resend code.');
      setOtpNotice(data.message || 'Verification code sent.');
    } catch (err) {
      setError(err?.message || 'Could not resend code.');
    }
  };

  const handleForgot = async (e) => {
    e.preventDefault();
    setLoading(true);
    clearError();
    try {
      const res = await fetch(getApiPath('/api/auth/forgot-password'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await readJsonSafely(res);
      if (!res.ok) throw new Error(data.message || 'Could not send reset email.');
      setForgotMessage(data.message || 'Check your inbox for a reset link.');
      setMode('forgot_sent');
    } catch (err) {
      setError(err?.message || 'Could not send reset email.');
    } finally {
      setLoading(false);
    }
  };

  const handleGoogle = useGoogleLogin({
    flow: 'implicit',
    ux_mode: 'popup',
    redirect_uri: 'https://cambridgeveritas.com/tools/signin',
    onSuccess: async (tokenResponse) => {
      setGoogleLoading(true);
      clearError();
      try {
        const res = await fetch(getApiPath('/api/auth/google'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            token: tokenResponse.access_token,
            ...(freeTrial ? { freeTrial: true } : {}),
            source: getCurrentTrackingSource(),
          }),
        });
        const data = await readJsonSafely(res);
        if (!res.ok) throw new Error(data.message || 'Google login failed');
        if (data?.requiresTwoFactor) {
          setEmail(data.email || email.trim());
          setOtpPurpose('login');
          setMode('otp');
          setOtp('');
          setOtpNotice(data.message || 'Enter the verification code sent to your email.');
          return;
        }
        onSuccess(data.user);
      } catch (err) {
        setError(err?.message || 'Google login failed. Please try again.');
      } finally {
        setGoogleLoading(false);
      }
    },
    onError: () => {
      setError('Google login failed. Please try again.');
      setGoogleLoading(false);
    }
  });

  const inputClass = "w-full px-4 py-3 rounded-xl border text-sm font-medium text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-[#D4B038]/30 focus:border-[#D4B038]/50 transition-all";

  return (
    <div className="w-full">
      <AnimatePresence mode="wait">

        {/* -- SIGN IN -- */}
        {mode === 'signin' && (
          <motion.div key="signin" initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }}>
            <h3 className="text-xl font-black text-white mb-1">Sign in to continue</h3>
            <p className="text-white/40 text-sm mb-5">Access your dashboard and test results.</p>

            {/* Google */}
            <button
              onClick={handleGoogle}
              disabled={googleLoading}
              className="w-full flex items-center justify-center gap-3 py-3 rounded-xl font-semibold text-sm transition-all mb-4 disabled:opacity-60"
              style={{ background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)', color: 'rgba(255,255,255,0.85)' }}
            >
              {googleLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <GoogleIcon />}
              Continue with Google
            </button>

            <div className="flex items-center gap-3 mb-4">
              <div className="flex-1 h-px" style={{ background: 'rgba(255,255,255,0.1)' }} />
              <span className="text-xs text-white/30 font-semibold">or</span>
              <div className="flex-1 h-px" style={{ background: 'rgba(255,255,255,0.1)' }} />
            </div>

            <form onSubmit={handleSignIn} className="space-y-3">
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Email</label>
                <input type="email" required placeholder="you@example.com" value={email} onChange={e => setEmail(e.target.value)} className={inputClass} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
              </div>
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Password</label>
                <div className="relative">
                  <input type={showPass ? 'text' : 'password'} required placeholder="********" value={password} onChange={e => setPassword(e.target.value)} className={`${inputClass} pr-11`} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
                  <button
                    type="button"
                    onClick={() => setShowPass(v => !v)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center text-white/90 hover:text-white bg-white/10 hover:bg-white/20 transition-colors"
                  >
                    {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {error && (
                <div className="flex items-center gap-2 text-red-400 text-xs font-semibold rounded-xl px-3 py-2.5" style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.2)' }}>
                  <AlertCircle className="w-4 h-4 flex-shrink-0" /> {error}
                </div>
              )}

              <button type="submit" disabled={loading}
                className="w-full py-3.5 rounded-xl font-extrabold text-sm flex items-center justify-center gap-2 transition-all disabled:opacity-60"
                style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22' }}>
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Lock className="w-4 h-4" /> Sign in <ArrowRight className="w-4 h-4" /></>}
              </button>
            </form>

            <div className={`flex items-center mt-4 ${allowRegister ? 'justify-between' : 'justify-end'}`}>
              <button onClick={() => { clearError(); setMode('forgot'); }} className="text-xs text-white/30 hover:text-white/60 font-semibold transition-colors">
                Forgot password?
              </button>
              {allowRegister && (
                <button onClick={() => { clearError(); if (onSignUp) { onSignUp(); } else { setMode('register'); } }} className="text-xs font-bold text-[#D4B038] hover:underline transition-colors">
                  Need an account? Sign up
                </button>
              )}
            </div>
          </motion.div>
        )}

        {/* -- REGISTER -- */}
        {allowRegister && mode === 'register' && (
          <motion.div key="register" initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }}>
            <h3 className="text-xl font-black text-white mb-1">Create your account</h3>
            <p className="sr-only">Create your account.</p>

            <form onSubmit={handleRegister} className="space-y-3">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">First Name</label>
                <input type="text" required placeholder="First name" value={firstName} onChange={e => setFirstName(e.target.value)} className={inputClass} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
              </div>
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Last Name</label>
                <input type="text" required placeholder="Last name" value={lastName} onChange={e => setLastName(e.target.value)} className={inputClass} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
              </div>
              </div>
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Phone (with country code)</label>
                <div className="relative flex h-[46px] rounded-xl border border-white/15 bg-white/10 focus-within:border-[#D4B038]/50 focus-within:ring-2 focus-within:ring-[#D4B038]/30">
                  <CountryCodeDropdown value={countryCode} onChange={setCountryCode} fitMenuToField />
                  <input
                    type="tel"
                    required
                    placeholder="07700 900000"
                    value={phone}
                    onChange={e => setPhone(e.target.value)}
                    inputMode="tel"
                    autoComplete="tel"
                    className="min-w-0 flex-1 rounded-r-xl border-0 bg-transparent px-4 py-3 text-sm font-medium text-white placeholder-white/30 outline-none"
                  />
                </div>
              </div>
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Email</label>
                <input type="email" required placeholder="you@example.com" value={email} onChange={e => setEmail(e.target.value)} className={inputClass} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
              </div>
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Password</label>
                <div className="relative">
                  <input type={showPass ? 'text' : 'password'} required placeholder="********" value={password} onChange={e => setPassword(e.target.value)} className={`${inputClass} pr-11`} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
                  <button
                    type="button"
                    onClick={() => setShowPass(v => !v)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full flex items-center justify-center text-white/90 hover:text-white bg-white/10 hover:bg-white/20 transition-colors"
                  >
                    {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              <div className="rounded-xl border border-white/15 bg-white/[0.06] p-3">
                <div className="mb-2 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-white/50">
                  <ShieldCheck className="h-4 w-4 text-[#D4B038]" /> Security verification
                </div>
                <TurnstileWidget
                  action="register"
                  resetKey={turnstileResetKey}
                  onVerify={setTurnstileToken}
                  onExpire={() => setTurnstileToken('')}
                  onError={() => setTurnstileToken('')}
                />
              </div>

              {error && (
                <div className="flex items-center gap-2 text-red-400 text-xs font-semibold rounded-xl px-3 py-2.5" style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.2)' }}>
                  <AlertCircle className="w-4 h-4 flex-shrink-0" /> {error}
                </div>
              )}

              <button type="submit" disabled={loading || !turnstileToken}
                className="w-full py-3.5 rounded-xl font-extrabold text-sm flex items-center justify-center gap-2 transition-all disabled:opacity-60"
                style={{ background: 'linear-gradient(135deg, #D4B038, #BFA030)', color: '#3D0F22' }}>
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><User className="w-4 h-4" /> Create Account <ArrowRight className="w-4 h-4" /></>}
              </button>
            </form>

            <div className="text-center mt-4">
              <button onClick={() => { clearError(); setMode('signin'); }} className="text-xs font-bold text-[#D4B038] hover:underline">
                Already have an account? Sign in
              </button>
            </div>
          </motion.div>
        )}

        {/* -- OTP VERIFICATION -- */}
        {mode === 'otp' && (
          <motion.div key="otp" initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }}>
            <h3 className="text-xl font-black text-white mb-1">Check your email</h3>
            <p className="text-white/40 text-sm mb-5">We sent a verification code to <strong className="text-white/70">{email}</strong></p>

            <form onSubmit={handleVerifyOtp} className="space-y-3">
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Verification Code</label>
                <input type="text" required placeholder="Enter 6-digit code" value={otp} onChange={e => setOtp(e.target.value)} className={`${inputClass} text-center text-lg tracking-widest`} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} maxLength={6} />
              </div>

              {otpNotice && (
                <div className="flex items-center gap-2 text-emerald-300 text-xs font-semibold rounded-xl px-3 py-2.5" style={{ background: 'rgba(16,185,129,0.15)', border: '1px solid rgba(16,185,129,0.3)' }}>
                  <CheckCircle2 className="w-4 h-4 flex-shrink-0" /> {otpNotice}
                </div>
              )}

              {error && (
                <div className="flex items-center gap-2 text-red-400 text-xs font-semibold rounded-xl px-3 py-2.5" style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.2)' }}>
                  <AlertCircle className="w-4 h-4 flex-shrink-0" /> {error}
                </div>
              )}

              <button type="submit" disabled={loading}
                className="w-full py-3.5 rounded-xl font-extrabold text-sm flex items-center justify-center gap-2 transition-all disabled:opacity-60"
                style={{ background: 'linear-gradient(135deg, #D4B038, #BFA030)', color: '#3D0F22' }}>
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><CheckCircle2 className="w-4 h-4" /> Verify &amp; Continue</>}
              </button>
            </form>

            <div className="text-center mt-4">
              <button onClick={handleResendOtp} className="text-xs text-white/30 hover:text-white/60 font-semibold transition-colors">
                Didn&apos;t receive it? Resend code
              </button>
            </div>
          </motion.div>
        )}

        {/* -- FORGOT PASSWORD -- */}
        {mode === 'forgot' && (
          <motion.div key="forgot" initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }}>
            <h3 className="text-xl font-black text-white mb-1">Reset your password</h3>
            <p className="text-white/40 text-sm mb-5">Enter your email and we&apos;ll send you a reset link.</p>

            <form onSubmit={handleForgot} className="space-y-3">
              <div>
                <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">Email</label>
                <input type="email" required placeholder="you@example.com" value={email} onChange={e => setEmail(e.target.value)} className={inputClass} style={{ background: 'rgba(255,255,255,0.07)', borderColor: 'rgba(255,255,255,0.12)' }} />
              </div>

              {error && (
                <div className="flex items-center gap-2 text-red-400 text-xs font-semibold rounded-xl px-3 py-2.5" style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.2)' }}>
                  <AlertCircle className="w-4 h-4 flex-shrink-0" /> {error}
                </div>
              )}

              <button type="submit" disabled={loading}
                className="w-full py-3.5 rounded-xl font-extrabold text-sm flex items-center justify-center gap-2 transition-all disabled:opacity-60"
                style={{ background: 'linear-gradient(135deg, #D4B038, #BFA030)', color: '#3D0F22' }}>
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Mail className="w-4 h-4" /> Send Reset Link</>}
              </button>
            </form>

            <div className="text-center mt-4">
              <button onClick={() => { clearError(); setMode('signin'); }} className="text-xs font-bold text-[#D4B038] hover:underline">
                Back to sign in
              </button>
            </div>
          </motion.div>
        )}

        {/* -- FORGOT SENT -- */}
        {mode === 'forgot_sent' && (
          <motion.div key="forgot_sent" initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }} className="text-center py-4">
            <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ background: 'rgba(16,185,129,0.15)', border: '1px solid rgba(16,185,129,0.3)' }}>
              <CheckCircle2 className="w-8 h-8 text-emerald-400" />
            </div>
            <h3 className="text-xl font-black text-white mb-2">Check your inbox</h3>
            <p className="text-white/40 text-sm mb-6">{forgotMessage || `We sent a password reset link to ${email}`}</p>
            <button onClick={() => { clearError(); setMode('signin'); }} className="text-sm font-bold text-[#D4B038] hover:underline">
              Back to sign in
            </button>
          </motion.div>
        )}

      </AnimatePresence>
    </div>
  );
}
