'use client';

import { useState, useRef, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { auth, db } from '@/lib/firebase';
import {
  RecaptchaVerifier,
  signInWithPhoneNumber,
  updatePassword,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  EmailAuthProvider,
  linkWithCredential,
} from 'firebase/auth';
import { doc, getDoc, setDoc, updateDoc } from 'firebase/firestore';
import { Phone, ArrowLeft, Loader2, Lock, KeyRound } from 'lucide-react';
import { toast } from '@/hooks/use-toast';
import Link from 'next/link';
import { useLanguage } from '@/hooks/use-language';
import { t } from '@/lib/i18n';

type AuthMode = 'otp' | 'password';
type Step = 'phone' | 'otp' | 'password_input' | 'set_password';

export default function AuthContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get('redirect') || '/dashboard';
  const isAdminRedirect = redirect === '/admin';
  const [mode, setMode] = useState<AuthMode>(isAdminRedirect ? 'password' : 'otp');
  const [step, setStep] = useState<Step>('phone');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [otp, setOtp] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [verificationId, setVerificationId] = useState('');
  const { lang } = useLanguage();
  const recaptchaRef = useRef<HTMLDivElement>(null);
  const recaptchaVerifierRef = useRef<RecaptchaVerifier | null>(null);

  const getEmailFromPhone = (phone: string) => {
    const digits = phone.replace(/[^0-9]/g, '');
    return `${digits}@once.app`;
  };

  const extractDigits = (phone: string) => phone.replace(/[^0-9]/g, '');
  const isValidPhone = (phone: string) => {
    const digits = extractDigits(phone);
    return digits.length >= 7;
  };
  const formatPhoneE164 = (phone: string) => {
    const digits = extractDigits(phone);
    return `+${digits}`;
  };

  useEffect(() => {
    if ((step === 'phone' || step === 'password_input') && recaptchaRef.current && !recaptchaVerifierRef.current) {
      recaptchaVerifierRef.current = new RecaptchaVerifier(auth, recaptchaRef.current, {
        size: 'invisible',
        callback: () => {},
      });
    }
  }, [step]);

  const handleSendOtp = async () => {
    if (!isValidPhone(phoneNumber)) {
      toast({ title: t(lang, 'invalidPhone'), variant: 'destructive' });
      return;
    }
    setLoading(true);
    try {
      const formattedNumber = formatPhoneE164(phoneNumber);
      const confirmation = await signInWithPhoneNumber(
        auth,
        formattedNumber,
        recaptchaVerifierRef.current!
      );
      setVerificationId(confirmation.verificationId);
      setStep('otp');
      toast({ title: t(lang, 'otpSent'), variant: 'success' });
    } catch (error: any) {
      if (error.code === 'auth/argument-error') {
        toast({
          title: t(lang, 'invalidPhoneFormat'),
          description: t(lang, 'invalidPhoneFormatDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/too-many-requests') {
        toast({
          title: t(lang, 'tooManyAttempts'),
          description: t(lang, 'tooManyAttemptsDesc'),
          variant: 'destructive',
        });
      } else {
        toast({ title: error.message || t(lang, 'failedSendOtp'), variant: 'destructive' });
      }
      recaptchaVerifierRef.current?.clear();
      recaptchaVerifierRef.current = null;
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async () => {
    if (!otp || otp.length < 4) {
      toast({ title: t(lang, 'invalidOtp'), variant: 'destructive' });
      return;
    }
    setLoading(true);
    try {
      const { PhoneAuthProvider, signInWithCredential } = await import('firebase/auth');
      const credential = PhoneAuthProvider.credential(verificationId, otp);
      const userCredential = await signInWithCredential(auth, credential);

      const userDoc = await getDoc(doc(db, 'users', userCredential.user.uid));
      const isAdmin = userDoc.exists() ? (userDoc.data()?.isAdmin || false) : false;
      const hasPassword = userDoc.exists() ? (userDoc.data()?.passwordSet || false) : false;

      if (!hasPassword) {
        // First login — ask to set password
        setStep('set_password');
        setLoading(false);
        return;
      }

      toast({ title: t(lang, 'welcomeToMomira'), variant: 'success' });
      router.push(isAdmin ? '/admin' : redirect);
    } catch (error: any) {
      if (error.code === 'auth/argument-error') {
        toast({ title: t(lang, 'invalidVerification'), variant: 'destructive' });
      } else if (error.code === 'auth/too-many-requests') {
        toast({
          title: t(lang, 'tooManyAttempts'),
          description: t(lang, 'tooManyAttemptsDesc'),
          variant: 'destructive',
        });
      } else {
        toast({ title: error.message || t(lang, 'invalidOtpCode'), variant: 'destructive' });
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSetPassword = async () => {
    if (!password || password.length < 6) {
      toast({ title: t(lang, 'passwordMinChars'), variant: 'destructive' });
      return;
    }
    setLoading(true);
    try {
      const user = auth.currentUser!;
      const email = getEmailFromPhone(phoneNumber);

      // Try to link email/password to existing phone user
      const emailCredential = EmailAuthProvider.credential(email, password);
      await linkWithCredential(user, emailCredential);

      // Mark password as set
      await updateDoc(doc(db, 'users', user.uid), {
        passwordSet: true,
        loginEmail: email,
      });

      toast({ title: t(lang, 'passwordSaved'), variant: 'success' });
      router.push(redirect);
    } catch (error: any) {
      if (error.code === 'auth/operation-not-allowed') {
        toast({
          title: t(lang, 'emailPasswordDisabled'),
          description: t(lang, 'emailPasswordDisabledDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/too-many-requests') {
        toast({
          title: t(lang, 'tooManyAttempts'),
          description: t(lang, 'tooManyAttemptsDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/provider-already-linked') {
        // Already linked, just update password
        try {
          await updatePassword(auth.currentUser!, password);
          await updateDoc(doc(db, 'users', auth.currentUser!.uid), {
            passwordSet: true,
            loginEmail: getEmailFromPhone(phoneNumber),
          });
          toast({ title: t(lang, 'passwordUpdated'), variant: 'success' });
          router.push(redirect);
        } catch (updateErr: any) {
          toast({ title: updateErr.message || t(lang, 'failedUpdatePassword'), variant: 'destructive' });
        }
      } else {
        toast({ title: error.message || t(lang, 'failedSavePassword'), variant: 'destructive' });
      }
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordLogin = async () => {
    if (!isValidPhone(phoneNumber)) {
      toast({ title: t(lang, 'invalidPhone'), variant: 'destructive' });
      return;
    }
    if (!password || password.length < 6) {
      toast({ title: t(lang, 'enterYourPassword'), variant: 'destructive' });
      return;
    }
    setLoading(true);
    try {
      const email = getEmailFromPhone(phoneNumber);
      if (!email || email === '@once.app') {
        toast({ title: t(lang, 'invalidPhoneNoCountry'), variant: 'destructive' });
        setLoading(false);
        return;
      }
      await signInWithEmailAndPassword(auth, email, password);
      toast({ title: t(lang, 'welcomeBack'), variant: 'success' });
      router.push(redirect);
    } catch (error: any) {
      if (error.code === 'auth/argument-error') {
        toast({
          title: t(lang, 'invalidPhoneNoCountry'),
          description: t(lang, 'invalidPhoneNoCountryDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/too-many-requests') {
        toast({
          title: t(lang, 'tooManyAttempts'),
          description: t(lang, 'tooManyAttemptsDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/invalid-credential' || error.code === 'auth/user-not-found') {
        toast({
          title: t(lang, 'invalidPhoneOrPassword'),
          description: t(lang, 'invalidPhoneOrPasswordDesc'),
          variant: 'destructive',
        });
      } else if (error.code === 'auth/operation-not-allowed') {
        toast({
          title: t(lang, 'emailPasswordDisabledAlt'),
          description: t(lang, 'emailPasswordDisabledAltDesc'),
          variant: 'destructive',
        });
      } else {
        toast({ title: error.message || t(lang, 'invalidPhoneOrPasswordAlt'), variant: 'destructive' });
      }
    } finally {
      setLoading(false);
    }
  };

  // Determine title based on step
  const getTitle = () => {
    switch (step) {
      case 'phone': return mode === 'otp' ? 'Momira' : t(lang, 'passwordAuth');
      case 'otp': return t(lang, 'verifyCode');
      case 'set_password': return t(lang, 'setPassword');
      case 'password_input': return t(lang, 'enterPassword');
    }
  };

  const getSubtitle = () => {
    switch (step) {
      case 'phone':
        return mode === 'otp'
          ? t(lang, 'enterPhone')
          : t(lang, 'enterPhone');
      case 'otp': return `${phoneNumber}`;
      case 'set_password': return t(lang, 'setPassword');
      case 'password_input': return `${phoneNumber}`;
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-6 bg-gradient-to-b from-zinc-950 via-zinc-900 to-zinc-950" dir={lang === 'ar' ? 'rtl' : 'ltr'}>
      {/* Background decoration */}
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_30%,rgba(99,102,241,0.08),transparent_60%)] pointer-events-none" />
      
      <div className="w-full max-w-sm relative z-10">
        <Link href="/" className="inline-flex items-center gap-2 text-zinc-400 hover:text-white mb-8 text-sm transition-colors">
          <ArrowLeft className={`h-4 w-4 ${lang === 'ar' ? 'rotate-180' : ''}`} />
          {t(lang, 'back')}
        </Link>

        <div className="mb-8 text-center">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 mb-4 shadow-lg shadow-indigo-500/30">
            <Phone className="h-7 w-7 text-white" />
          </div>
          <h1 className="text-3xl font-bold mb-2 text-white">{getTitle()}</h1>
          <p className="text-zinc-400 text-sm">{getSubtitle()}</p>
        </div>

        {/* Mode toggle */}
        {step === 'phone' && !isAdminRedirect && (
          <div className="flex gap-1 mb-6 p-1 rounded-xl bg-zinc-900/50 border border-zinc-800">
            <button
              onClick={() => setMode('otp')}
              className={`flex-1 h-10 rounded-lg text-sm font-medium transition-all ${
                mode === 'otp'
                  ? 'bg-indigo-500 text-white shadow-md shadow-indigo-500/20'
                  : 'text-zinc-400 hover:text-white'
              }`}
            >
              <span className="flex items-center justify-center gap-2">
                <Phone className="h-4 w-4" /> {t(lang, 'phoneAuth')}
              </span>
            </button>
            <button
              onClick={() => setMode('password')}
              className={`flex-1 h-10 rounded-lg text-sm font-medium transition-all ${
                mode === 'password'
                  ? 'bg-indigo-500 text-white shadow-md shadow-indigo-500/20'
                  : 'text-zinc-400 hover:text-white'
              }`}
            >
              <span className="flex items-center justify-center gap-2">
                <Lock className="h-4 w-4" /> {t(lang, 'passwordAuth')}
              </span>
            </button>
          </div>
        )}

        {/* Phone + OTP flow */}
        {step === 'phone' && mode === 'otp' && (
          <div className="space-y-4">
            <div className="relative">
              <Phone className="absolute start-3 top-1/2 -translate-y-1/2 h-5 w-5 text-zinc-500" />
              <input
                type="tel"
                placeholder="+966501234567"
                value={phoneNumber}
                onChange={(e) => setPhoneNumber(e.target.value)}
                dir="ltr"
                className="w-full h-12 ps-11 pe-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 transition-all"
              />
            </div>
            <button
              onClick={handleSendOtp}
              disabled={loading}
              className="w-full h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-semibold flex items-center justify-center gap-2 hover:from-indigo-600 hover:to-purple-700 transition-all shadow-lg shadow-indigo-500/30 disabled:opacity-50"
            >
              {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : t(lang, 'sendCode')}
            </button>
          </div>
        )}

        {/* Phone + Password flow */}
        {step === 'phone' && mode === 'password' && (
          <div className="space-y-4">
            <div className="relative">
              <Phone className="absolute start-3 top-1/2 -translate-y-1/2 h-5 w-5 text-zinc-500" />
              <input
                type="tel"
                placeholder="+966501234567"
                value={phoneNumber}
                onChange={(e) => setPhoneNumber(e.target.value)}
                dir="ltr"
                className="w-full h-12 ps-11 pe-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 transition-all"
              />
            </div>
            <div className="relative">
              <Lock className="absolute start-3 top-1/2 -translate-y-1/2 h-5 w-5 text-zinc-500" />
              <input
                type="password"
                placeholder={lang === 'ar' ? 'كلمة المرور' : 'Password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full h-12 ps-11 pe-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 transition-all"
              />
            </div>
            <button
              onClick={handlePasswordLogin}
              disabled={loading}
              className="w-full h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-semibold flex items-center justify-center gap-2 hover:from-indigo-600 hover:to-purple-700 transition-all shadow-lg shadow-indigo-500/30 disabled:opacity-50"
            >
              {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : t(lang, 'login')}
            </button>
          </div>
        )}

        {/* OTP verification */}
        {step === 'otp' && (
          <div className="space-y-4">
            <input
              type="text"
              placeholder={lang === 'ar' ? 'أدخل الرمز' : 'Enter OTP'}
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              maxLength={6}
              className="w-full h-14 px-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 transition-all text-center text-2xl tracking-[0.5em] font-mono"
            />
            <button
              onClick={handleVerifyOtp}
              disabled={loading}
              className="w-full h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-semibold flex items-center justify-center gap-2 hover:from-indigo-600 hover:to-purple-700 transition-all shadow-lg shadow-indigo-500/30 disabled:opacity-50"
            >
              {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : (lang === 'ar' ? 'تحقق' : 'Verify')}
            </button>
            <button
              onClick={() => setStep('phone')}
              className="w-full h-12 rounded-xl border border-zinc-800 text-zinc-300 font-medium hover:bg-zinc-900 hover:border-zinc-700 transition-colors"
            >
              {lang === 'ar' ? 'تغيير الرقم' : 'Change number'}
            </button>
          </div>
        )}

        {/* Set password after first OTP */}
        {step === 'set_password' && (
          <div className="space-y-4">
            <div className="relative">
              <KeyRound className="absolute start-3 top-1/2 -translate-y-1/2 h-5 w-5 text-zinc-500" />
              <input
                type="password"
                placeholder={lang === 'ar' ? 'أنشئ كلمة مرور (6 أحرف على الأقل)' : 'Create password (min 6 chars)'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full h-12 ps-11 pe-4 rounded-xl bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 transition-all"
              />
            </div>
            <button
              onClick={handleSetPassword}
              disabled={loading}
              className="w-full h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-semibold flex items-center justify-center gap-2 hover:from-indigo-600 hover:to-purple-700 transition-all shadow-lg shadow-indigo-500/30 disabled:opacity-50"
            >
              {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : t(lang, 'setPassword')}
            </button>
            <button
              onClick={() => router.push(redirect)}
              className="w-full h-12 rounded-xl border border-zinc-800 text-zinc-300 font-medium hover:bg-zinc-900 hover:border-zinc-700 transition-colors"
            >
              {lang === 'ar' ? 'تخطي' : 'Skip for now'}
            </button>
          </div>
        )}

        <div ref={recaptchaRef} className="mt-4" />
      </div>
    </div>
  );
}
