'use client';

import React, { useState, useEffect } from 'react';
import { X, ArrowLeft, Shield, Sparkles, User, Mail, UserPlus, CheckCircle2 } from 'lucide-react';
import { authApi } from '@/lib/api';
import { savePlatformSession } from '@/lib/auth';
import { toast } from 'sonner';

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

type AuthStep = 'phone' | 'otp' | 'signup' | 'email_otp';

interface CountryItem {
  name: string;
  code: string;
  dial_code: string;
  flag: string;
  min_length: number;
  max_length: number;
}

const COUNTRIES: CountryItem[] = [
  { name: 'India', code: 'IN', dial_code: '91', flag: '🇮🇳', min_length: 10, max_length: 10 },
  { name: 'United States', code: 'US', dial_code: '1', flag: '🇺🇸', min_length: 10, max_length: 10 },
  { name: 'United Kingdom', code: 'GB', dial_code: '44', flag: '🇬🇧', min_length: 10, max_length: 10 },
  { name: 'United Arab Emirates', code: 'AE', dial_code: '971', flag: '🇦🇪', min_length: 9, max_length: 9 },
  { name: 'Canada', code: 'CA', dial_code: '1', flag: '🇨🇦', min_length: 10, max_length: 10 },
  { name: 'Australia', code: 'AU', dial_code: '61', flag: '🇦🇺', min_length: 9, max_length: 9 },
  { name: 'Saudi Arabia', code: 'SA', dial_code: '966', flag: '🇸🇦', min_length: 9, max_length: 9 },
  { name: 'Singapore', code: 'SG', dial_code: '65', flag: '🇸🇬', min_length: 8, max_length: 8 },
  { name: 'Germany', code: 'DE', dial_code: '49', flag: '🇩🇪', min_length: 10, max_length: 11 },
  { name: 'France', code: 'FR', dial_code: '33', flag: '🇫🇷', min_length: 9, max_length: 9 },
];

export function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps) {
  const [step, setStep] = useState<AuthStep>('phone');
  const [countryCode, setCountryCode] = useState('91');
  const [phone, setPhone] = useState('');
  const [otp, setOtp] = useState(['', '', '', '']);
  const [loading, setLoading] = useState(false);
  const [timer, setTimer] = useState(30);
  const [canResend, setCanResend] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Signup form states
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [gender, setGender] = useState<'male' | 'female' | 'other' | ''>('');
  const [referralCode, setReferralCode] = useState('');
  const [emailOtp, setEmailOtp] = useState(['', '', '', '']);

  const selectedCountry = COUNTRIES.find((c) => c.dial_code === countryCode) || COUNTRIES[0];

  useEffect(() => {
    let interval: any;
    if ((step === 'otp' || step === 'email_otp') && timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => {
          if (prev <= 1) {
            setCanResend(true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [step, timer]);

  if (!isOpen) return null;

  const validateEmail = (val: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val);
  };

  const handleCountrySelect = (code: string) => {
    setCountryCode(code);
    setPhone('');
    setError(null);
  };

  const handlePhoneChange = (val: string) => {
    const clean = val.replace(/\D/g, '').slice(0, selectedCountry.max_length);
    setPhone(clean);
  };

  const handlePhoneSubmit = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setError(null);
    const cleanPhone = phone.trim().replace(/\D/g, '');

    if (cleanPhone.length < selectedCountry.min_length) {
      const msg = `Please enter a valid ${selectedCountry.name} phone number (${selectedCountry.min_length} digits)`;
      setError(msg);
      toast.error(msg);
      return;
    }

    setLoading(true);
    try {
      await authApi.continueWithPhone({
        phone: cleanPhone,
        country_code: countryCode,
        type: 'customer',
      });
      setStep('otp');
      setTimer(30);
      setCanResend(false);
      toast.success('Verification code sent');
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || 'Failed to send OTP';
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleOtpChange = (index: number, value: string) => {
    const cleanVal = value.replace(/\D/g, '').slice(-1);
    const newOtp = [...otp];
    newOtp[index] = cleanVal;
    setOtp(newOtp);

    if (cleanVal && index < 3) {
      const nextInput = document.getElementById(`auth-modal-otp-${index + 1}`);
      nextInput?.focus();
    }

    if (cleanVal && index === 3 && newOtp.every((d) => d.length === 1)) {
      handleOtpSubmit(newOtp.join(''));
    }
  };

  const handleOtpKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      const prevInput = document.getElementById(`auth-modal-otp-${index - 1}`);
      prevInput?.focus();
    }
  };

  const handleOtpSubmit = async (fullOtp?: string) => {
    setError(null);
    const finalOtp = fullOtp || otp.join('');

    if (finalOtp.length < 4) {
      setError('Please enter 4-digit verification code');
      toast.error('Please enter 4-digit verification code');
      return;
    }

    setLoading(true);
    try {
      const res = await authApi.verifyPhone({
        otp: finalOtp,
        device_type: 'web',
        fcm_token: '',
      });

      const token = res?.access_token || res?.token || res?.data?.access_token;
      const user = res?.data || res?.user;
      const isEmailVerified = res?.data?.is_email_verify ?? true;

      // If new user or email not verified -> proceed to Signup profile details
      if (!isEmailVerified) {
        setStep('signup');
        toast.info('Please complete your profile to continue');
        return;
      }

      if (token) {
        savePlatformSession(token, user);
        toast.success('Successfully logged in!');
        if (onSuccess) onSuccess();
        onClose();
        window.dispatchEvent(
          new CustomEvent('READY_MFE_EVENT', {
            detail: { type: 'MFE_AUTH_LOGIN', payload: { token, user } },
          })
        );
      }
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || 'Invalid or expired OTP';
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleSignupSubmit = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setError(null);

    if (!name.trim()) {
      setError('Please enter your full name');
      toast.error('Please enter your full name');
      return;
    }

    if (!email.trim() || !validateEmail(email.trim())) {
      setError('Please enter a valid email address');
      toast.error('Please enter a valid email address');
      return;
    }

    setLoading(true);
    try {
      await authApi.editProfile({
        name: name.trim(),
        email: email.trim(),
        gender: gender || undefined,
        applied_referral_code: referralCode.trim() || undefined,
      });

      setStep('email_otp');
      setTimer(30);
      setCanResend(false);
      toast.success('Verification code sent to your email');
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || 'Failed to update profile details';
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleEmailOtpChange = (index: number, value: string) => {
    const cleanVal = value.replace(/\D/g, '').slice(-1);
    const newOtp = [...emailOtp];
    newOtp[index] = cleanVal;
    setEmailOtp(newOtp);

    if (cleanVal && index < 3) {
      const nextInput = document.getElementById(`auth-modal-email-otp-${index + 1}`);
      nextInput?.focus();
    }

    if (cleanVal && index === 3 && newOtp.every((d) => d.length === 1)) {
      handleEmailOtpSubmit(newOtp.join(''));
    }
  };

  const handleEmailOtpKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !emailOtp[index] && index > 0) {
      const prevInput = document.getElementById(`auth-modal-email-otp-${index - 1}`);
      prevInput?.focus();
    }
  };

  const handleEmailOtpSubmit = async (fullOtp?: string) => {
    setError(null);
    const finalOtp = fullOtp || emailOtp.join('');

    if (finalOtp.length < 4) {
      setError('Please enter 4-digit email verification code');
      toast.error('Please enter 4-digit email verification code');
      return;
    }

    setLoading(true);
    try {
      const res = await authApi.verifyEmail({
        otp: finalOtp,
        email: email.trim(),
      });

      const token = res?.access_token || res?.token || res?.data?.access_token;
      let user = res?.data || res?.user;

      // Immediately fetch latest user profile data from backend
      try {
        const profileRes = await authApi.getProfile();
        if (profileRes?.data || profileRes) {
          user = profileRes?.data || profileRes;
        }
      } catch (profileErr) {
        console.warn('Failed to fetch user profile after email verify:', profileErr);
      }

      if (token) {
        savePlatformSession(token, user);
      }
      toast.success('Registration completed successfully!');
      if (onSuccess) onSuccess();
      onClose();
      window.dispatchEvent(
        new CustomEvent('READY_MFE_EVENT', {
          detail: { type: 'MFE_AUTH_LOGIN', payload: { token, user } },
        })
      );
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || 'Invalid or expired email OTP';
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    setError(null);
    if (step === 'otp') {
      setStep('phone');
      setOtp(['', '', '', '']);
    } else if (step === 'signup') {
      setStep('otp');
    } else if (step === 'email_otp') {
      setStep('signup');
      setEmailOtp(['', '', '', '']);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="relative w-full max-w-md bg-white rounded-3xl p-6 sm:p-8 shadow-2xl border border-neutral-200">

        {/* Header Controls */}
        <div className="flex items-center justify-between mb-6">
          {step !== 'phone' ? (
            <button
              onClick={handleBack}
              className="flex items-center justify-center h-9 w-9 rounded-full bg-neutral-100 hover:bg-neutral-200 text-neutral-800 transition"
            >
              <ArrowLeft className="h-4 w-4" />
            </button>
          ) : (
            <div className="h-9 w-9" />
          )}

          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-black text-white shadow-sm">
            <Sparkles className="h-5 w-5" />
          </div>

          <button
            onClick={onClose}
            className="flex items-center justify-center h-9 w-9 rounded-full bg-neutral-100 hover:bg-neutral-200 text-neutral-800 transition"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* STEP 1: Phone */}
        {step === 'phone' && (
          <form onSubmit={handlePhoneSubmit} className="space-y-6">
            <div className="text-center">
              <h2 className="text-2xl font-black text-black">Welcome to ReadyGO</h2>
              <p className="text-xs text-neutral-500 mt-1">
                Enter your mobile phone number to sign in or create an account
              </p>
            </div>

            {error && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-xs text-red-700">
                {error}
              </div>
            )}

            <div className="space-y-3">
              <label className="block text-xs font-semibold uppercase tracking-wider text-neutral-600">
                Mobile Number
              </label>

              <div className="flex gap-2">
                <select
                  value={countryCode}
                  onChange={(e) => handleCountrySelect(e.target.value)}
                  className="rounded-2xl border border-neutral-300 bg-neutral-50 px-3 py-3.5 text-sm font-semibold text-black focus:border-black focus:outline-none"
                >
                  {COUNTRIES.map((c) => (
                    <option key={c.code} value={c.dial_code}>
                      {c.flag} +{c.dial_code} ({c.code})
                    </option>
                  ))}
                </select>

                <div className="relative flex-1">
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => handlePhoneChange(e.target.value)}
                    maxLength={selectedCountry.max_length}
                    placeholder={`Enter ${selectedCountry.min_length} digit number`}
                    autoFocus
                    required
                    className="w-full rounded-2xl border border-neutral-300 bg-neutral-50 px-4 py-3.5 text-sm font-medium text-black placeholder-neutral-400 focus:border-black focus:outline-none"
                  />
                </div>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading || phone.trim().length < selectedCountry.min_length}
              className="flex items-center justify-center w-full rounded-full bg-black py-4 text-sm font-bold text-white shadow-md hover:bg-neutral-800 transition disabled:opacity-40"
            >
              {loading ? 'Sending Code...' : 'Continue'}
            </button>

            <div className="flex items-center justify-center gap-2 text-xs text-neutral-500">
              <Shield className="h-3.5 w-3.5 text-neutral-400" />
              <span>Your personal data is encrypted & secured</span>
            </div>
          </form>
        )}

        {/* STEP 2: Phone OTP */}
        {step === 'otp' && (
          <div className="space-y-6">
            <div className="text-center">
              <h2 className="text-2xl font-black text-black">Verify Phone</h2>
              <p className="text-xs text-neutral-500 mt-1">
                Enter the 4-digit code sent to <span className="font-bold text-black">+{countryCode} {phone}</span>
              </p>
            </div>

            {error && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-xs text-red-700">
                {error}
              </div>
            )}

            <div className="flex justify-center gap-3">
              {[0, 1, 2, 3].map((index) => (
                <input
                  key={index}
                  id={`auth-modal-otp-${index}`}
                  type="text"
                  maxLength={1}
                  value={otp[index]}
                  onChange={(e) => handleOtpChange(index, e.target.value)}
                  onKeyDown={(e) => handleOtpKeyDown(index, e)}
                  className="h-14 w-14 rounded-2xl border border-neutral-300 bg-neutral-100 text-center text-xl font-black text-black focus:border-black focus:bg-white focus:outline-none"
                />
              ))}
            </div>

            <div className="text-center text-xs text-neutral-500">
              {canResend ? (
                <button
                  type="button"
                  onClick={() => handlePhoneSubmit()}
                  className="font-bold text-black hover:underline"
                >
                  Resend OTP code
                </button>
              ) : (
                <p>
                  Resend code in <span className="font-bold text-black">{timer}s</span>
                </p>
              )}
            </div>

            <div className="rounded-2xl bg-neutral-100 p-2.5 text-center text-xs font-semibold text-neutral-600">
              Your OTP is <span className="font-mono font-bold text-black">1234</span>
            </div>

            <button
              type="button"
              onClick={() => handleOtpSubmit()}
              disabled={loading || otp.join('').length < 4}
              className="flex items-center justify-center w-full rounded-full bg-black py-4 text-sm font-bold text-white shadow-md hover:bg-neutral-800 transition disabled:opacity-40"
            >
              {loading ? 'Verifying...' : 'Verify & Continue'}
            </button>
          </div>
        )}

        {/* STEP 3: Complete Signup Profile Details */}
        {step === 'signup' && (
          <form onSubmit={handleSignupSubmit} className="space-y-4">
            <div className="text-center">
              <h2 className="text-2xl font-black text-black">Complete Signup</h2>
              <p className="text-xs text-neutral-500 mt-1">
                Please enter your details to set up your ReadyGO account
              </p>
            </div>

            {error && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-xs text-red-700">
                {error}
              </div>
            )}

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-neutral-700">
                Full Name *
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-neutral-400">
                  <User className="h-4 w-4" />
                </div>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value.replace(/[^a-zA-Z\s]/g, ''))}
                  placeholder="John Doe"
                  required
                  className="w-full rounded-2xl border border-neutral-300 bg-neutral-50 pl-10 pr-4 py-3 text-sm text-black placeholder-neutral-400 focus:border-black focus:outline-none"
                />
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-neutral-700">
                Email Address *
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-neutral-400">
                  <Mail className="h-4 w-4" />
                </div>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="name@example.com"
                  required
                  className="w-full rounded-2xl border border-neutral-300 bg-neutral-50 pl-10 pr-4 py-3 text-sm text-black placeholder-neutral-400 focus:border-black focus:outline-none"
                />
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-neutral-700">
                Gender (Optional)
              </label>
              <div className="grid grid-cols-3 gap-2">
                {[
                  { label: 'Male', value: 'male' },
                  { label: 'Female', value: 'female' },
                  { label: 'Other', value: 'other' },
                ].map((g) => (
                  <button
                    key={g.value}
                    type="button"
                    onClick={() => setGender((prev) => (prev === g.value ? '' : (g.value as any)))}
                    className={`py-2.5 rounded-xl text-xs font-bold transition-all border ${gender === g.value
                        ? 'bg-black text-white border-black shadow-sm'
                        : 'bg-neutral-50 border-neutral-200 text-neutral-700 hover:bg-neutral-100'
                      }`}
                  >
                    {g.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-neutral-700">
                Referral Code (Optional)
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-neutral-400">
                  <UserPlus className="h-4 w-4" />
                </div>
                <input
                  type="text"
                  value={referralCode}
                  onChange={(e) => setReferralCode(e.target.value)}
                  placeholder="Enter referral code"
                  className="w-full rounded-2xl border border-neutral-300 bg-neutral-50 pl-10 pr-4 py-3 text-sm font-mono text-black placeholder-neutral-400 focus:border-black focus:outline-none"
                />
              </div>
            </div>

            <button
              type="submit"
              disabled={loading || !name.trim() || !email.trim()}
              className="flex items-center justify-center w-full rounded-full bg-black py-4 text-sm font-bold text-white shadow-md hover:bg-neutral-800 transition disabled:opacity-40 mt-2"
            >
              {loading ? 'Submitting Details...' : 'Complete Signup'}
            </button>
          </form>
        )}

        {/* STEP 4: Email OTP Verification */}
        {step === 'email_otp' && (
          <div className="space-y-6">
            <div className="text-center">
              <h2 className="text-2xl font-black text-black">Verify Email</h2>
              <p className="text-xs text-neutral-500 mt-1">
                Enter the 4-digit code sent to <span className="font-bold text-black">{email}</span>
              </p>
            </div>

            {error && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-xs text-red-700">
                {error}
              </div>
            )}

            <div className="flex justify-center gap-3">
              {[0, 1, 2, 3].map((index) => (
                <input
                  key={index}
                  id={`auth-modal-email-otp-${index}`}
                  type="text"
                  maxLength={1}
                  value={emailOtp[index]}
                  onChange={(e) => handleEmailOtpChange(index, e.target.value)}
                  onKeyDown={(e) => handleEmailOtpKeyDown(index, e)}
                  className="h-14 w-14 rounded-2xl border border-neutral-300 bg-neutral-100 text-center text-xl font-black text-black focus:border-black focus:bg-white focus:outline-none"
                />
              ))}
            </div>

            <div className="text-center text-xs text-neutral-500">
              {canResend ? (
                <button
                  type="button"
                  onClick={() => handleSignupSubmit()}
                  className="font-bold text-black hover:underline"
                >
                  Resend email OTP
                </button>
              ) : (
                <p>
                  Resend code in <span className="font-bold text-black">{timer}s</span>
                </p>
              )}
            </div>

            <div className="rounded-2xl bg-neutral-100 p-2.5 text-center text-xs font-semibold text-neutral-600">
              Your OTP is <span className="font-mono font-bold text-black">1234</span>
            </div>

            <button
              type="button"
              onClick={() => handleEmailOtpSubmit()}
              disabled={loading || emailOtp.join('').length < 4}
              className="flex items-center justify-center w-full rounded-full bg-black py-4 text-sm font-bold text-white shadow-md hover:bg-neutral-800 transition disabled:opacity-40"
            >
              {loading ? 'Verifying Email...' : 'Verify & Finish'}
            </button>
          </div>
        )}

      </div>
    </div>
  );
}

