'use client';

/**
 * Authentication Modal — Email + Password + Cloudflare Turnstile + Password Recovery
 *
 * Features:
 * - Wired to POST /login (email + password + cf-turnstile-response)
 * - Password recovery flow wired to POST /api/auth/forgot-password
 * - Independent Cloudflare Turnstile Captcha on each step, requiring verification before submit
 * - Auto-hides captcha upon successful verification and displays "Security check complete" badge
 * - Fully resets captcha verification when switching between Login and Reset Password steps
 * - URL param auto-opening (?auth=login, ?auth=forgot_password) for legacy link parity
 * - Primary brand button hover styling (bg-brand-500 / hover:bg-brand-600 / shadow-brand-500/25)
 * - Preserves all original layout, modal responsiveness, animations, and typography.
 */

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Mail,
  User as UserIcon,
  RotateCw,
  CheckCircle2,
  KeyRound,
  ArrowLeft,
  ShieldCheck,
} from 'lucide-react';
import {
  ResponsiveModal,
  ResponsiveModalContent,
  ResponsiveModalHeader,
  ResponsiveModalTitle,
  ResponsiveModalDescription,
} from '@/components/ui/responsive-modal';
import { Input } from '@/components/ui/input';
import { useAuthStore } from '@/lib/stores/useAuthStore';
import { TurnstileWidget } from '@/components/auth/TurnstileWidget';

interface AuthModalProps {
  locale: string;
}

type AuthStep = 'login' | 'forgot_password' | 'forgot_password_success' | 'success';

export function AuthModal({ locale }: AuthModalProps) {
  const { isAuthModalOpen, authModalMode, closeAuthModal, openAuthModal, setUser } = useAuthStore();
  const searchParams = useSearchParams();
  const isAr = locale === 'ar';
  const t = useTranslations('authModal');

  // Translation helper with locale fallback
  const str = (key: Parameters<typeof t>[0], fallbackEn: string, fallbackAr: string): string => {
    try {
      const val = t(key);
      if (val && typeof val === 'string' && val !== `authModal.${key}` && val !== key) {
        return val;
      }
    } catch {
      // Fall back to default
    }
    return isAr ? fallbackAr : fallbackEn;
  };

  const [step, setStep] = useState<AuthStep>('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Cloudflare Turnstile state
  const [turnstileToken, setTurnstileToken] = useState<string>('');
  const [isTurnstileVerified, setIsTurnstileVerified] = useState<boolean>(false);

  // Step transition helper that always resets captcha verification
  const switchStep = (newStep: AuthStep) => {
    setStep(newStep);
    setError(null);
    setTurnstileToken('');
    setIsTurnstileVerified(false);
  };

  // Sync mode from store when modal opens
  useEffect(() => {
    if (isAuthModalOpen) {
      if (authModalMode === 'forgot_password') {
        switchStep('forgot_password');
      } else {
        switchStep('login');
      }
    }
  }, [isAuthModalOpen, authModalMode]);

  // Support legacy URLs via query parameters (?auth=login, ?auth=forgot_password)
  useEffect(() => {
    const authParam = searchParams.get('auth');
    if (authParam === 'login') {
      openAuthModal('login');
    } else if (
      authParam === 'forgot_password' ||
      authParam === 'recover_password' ||
      authParam === 'forgotpassword'
    ) {
      openAuthModal('forgot_password');
    }
  }, [searchParams, openAuthModal]);

  const handleModalClose = () => {
    switchStep('login');
    setEmail('');
    setPassword('');
    setIsLoading(false);
    closeAuthModal();
  };

  /**
   * POST /login — email + password + turnstile token
   */
  const handleLoginSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isTurnstileVerified) {
      setError(
        isAr ? 'يرجى إكمال التحقق الأمني أولاً' : 'Please complete the security check first'
      );
      return;
    }

    const cleanEmail = email.trim();
    if (!cleanEmail) {
      setError(isAr ? 'يرجى إدخال البريد الإلكتروني' : 'Please enter your email address');
      return;
    }
    if (!password) {
      setError(isAr ? 'يرجى إدخال كلمة المرور' : 'Please enter your password');
      return;
    }

    setError(null);
    setIsLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          email: cleanEmail,
          password,
          'cf-turnstile-response': turnstileToken || undefined,
        }),
      });

      const json = await res.json();

      if (!res.ok) {
        const msg =
          json?.message ||
          (isAr
            ? 'البريد الإلكتروني أو كلمة المرور غير صحيحة'
            : 'Invalid email or password. Please try again.');
        setError(msg);
        setIsLoading(false);
        setIsTurnstileVerified(false);
        setTurnstileToken('');
        return;
      }

      const userData = json?.data;
      if (!userData?.api_token) {
        setError(isAr ? 'حدث خطأ أثناء تسجيل الدخول' : 'Login failed. Please try again.');
        setIsLoading(false);
        return;
      }

      setUser(
        {
          id: userData.id,
          email: userData.email,
          first_name: userData.first_name || '',
          last_name: userData.last_name || '',
          user_type: userData.user_type,
          avatar: userData.profile_image || undefined,
          phone: userData.contact_number || userData.phone || undefined,
          contact_number: userData.contact_number || userData.phone || undefined,
        },
        userData.api_token
      );

      const userType = String(userData.user_type || 'user').toLowerCase();
      const isStaffOrProvider = ['provider', 'handyman', 'admin', 'demo_admin', 'agent'].includes(userType);

      setStep('success');
      setIsLoading(false);

      setTimeout(() => {
        handleModalClose();
        if (isStaffOrProvider) {
          window.location.href = '/home';
        }
      }, 1200);
    } catch {
      setError(
        isAr
          ? 'تعذّر الاتصال. يرجى التحقق من الاتصال بالإنترنت.'
          : 'Connection failed. Please check your internet connection.'
      );
      setIsLoading(false);
    }
  };

  /**
   * POST /api/forgot-password — password recovery request
   */
  const handleForgotPasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isTurnstileVerified) {
      setError(
        isAr ? 'يرجى إكمال التحقق الأمني أولاً' : 'Please complete the security check first'
      );
      return;
    }

    const cleanEmail = email.trim();
    if (!cleanEmail) {
      setError(isAr ? 'يرجى إدخال البريد الإلكتروني' : 'Please enter your email address');
      return;
    }

    setError(null);
    setIsLoading(true);

    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          email: cleanEmail,
          'cf-turnstile-response': turnstileToken || undefined,
        }),
      });

      const json = await res.json();

      if (!res.ok) {
        const msg =
          json?.message ||
          (isAr
            ? 'تعذر إرسال رابط الاستعادة. يرجى التحقق من البريد الإلكتروني.'
            : 'Unable to send password reset link. Please verify your email.');
        setError(msg);
        setIsLoading(false);
        setIsTurnstileVerified(false);
        setTurnstileToken('');
        return;
      }

      setIsLoading(false);
      setStep('forgot_password_success');
    } catch {
      setError(
        isAr
          ? 'تعذّر إرسال الطلب. يرجى التحقق من الاتصال بالإنترنت.'
          : 'Failed to send request. Please check your connection.'
      );
      setIsLoading(false);
    }
  };

  return (
    <ResponsiveModal open={isAuthModalOpen} onOpenChange={handleModalClose}>
      <ResponsiveModalContent className="max-w-md rounded-3xl p-6 sm:p-8">
        <AnimatePresence mode="wait" initial={false}>
          {/* ─────────────────────────────────────────────────────────────
              STATE 1: LOGIN (Email + Password + Turnstile)
             ───────────────────────────────────────────────────────────── */}
          {step === 'login' && (
            <motion.div
              key="step-login"
              initial={{ opacity: 0, x: -16 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -16 }}
              transition={{ duration: 0.2 }}
              className="space-y-6"
            >
              <ResponsiveModalHeader className="text-center sm:text-start mb-0">
                <ResponsiveModalTitle className="text-2xl font-extrabold text-zinc-900 dark:text-white tracking-tight">
                  {str('title', 'Welcome to ShineCode', 'مرحباً بكِ في شاين كود')}
                </ResponsiveModalTitle>
                <ResponsiveModalDescription className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                  {str('subtitle', 'Log in to continue.', 'سجلي الدخول للمتابعة.')}
                </ResponsiveModalDescription>
              </ResponsiveModalHeader>

              {error && (
                <div className="p-3 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-xl text-rose-700 dark:text-rose-300 text-xs font-medium">
                  {error}
                </div>
              )}

              <form onSubmit={handleLoginSubmit} className="space-y-4">
                {/* Email Field */}
                <div className="space-y-1.5">
                  <label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
                    <Mail className="w-3.5 h-3.5 text-zinc-400" />
                    <span>{str('emailLabel', 'Email Address', 'البريد الإلكتروني')} *</span>
                  </label>
                  <Input
                    id="auth-email"
                    type="email"
                    autoFocus
                    required
                    autoComplete="email"
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value);
                      if (error) setError(null);
                    }}
                    placeholder={str('emailPlaceholder', 'you@example.com', 'example@example.com')}
                    className="h-12 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700"
                  />
                </div>

                {/* Password Field with Forgot Password Link */}
                <div className="space-y-1.5">
                  <div className="flex items-center justify-between">
                    <label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
                      <UserIcon className="w-3.5 h-3.5 text-zinc-400" />
                      <span>{str('passwordLabel', 'Password', 'كلمة المرور')} *</span>
                    </label>
                    <button
                      type="button"
                      onClick={() => switchStep('forgot_password')}
                      className="text-xs font-semibold text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300 transition-colors cursor-pointer"
                    >
                      {str('forgotPasswordLink', 'Forgot password?', 'نسيتِ كلمة المرور؟')}
                    </button>
                  </div>
                  <Input
                    id="auth-password"
                    type="password"
                    required
                    autoComplete="current-password"
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      if (error) setError(null);
                    }}
                    placeholder={str('passwordPlaceholder', '••••••••', '••••••••')}
                    className="h-12 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700"
                  />
                </div>

                {/* Turnstile Captcha Widget */}
                <TurnstileWidget
                  containerId="turnstile-login-container"
                  onVerify={(token) => {
                    setTurnstileToken(token);
                    setIsTurnstileVerified(true);
                  }}
                  onExpire={() => {
                    setTurnstileToken('');
                    setIsTurnstileVerified(false);
                  }}
                  isVerified={isTurnstileVerified}
                  isAr={isAr}
                />

                {/* Primary CTA with Primary Brand Colors & Hover */}
                <button
                  type="submit"
                  disabled={isLoading || !isTurnstileVerified}
                  className="w-full bg-brand-500 hover:bg-brand-600 active:bg-brand-700 text-white rounded-xl py-3.5 font-bold mt-4 transition-all duration-200 shadow-md hover:shadow-brand-500/25 active:scale-[0.99] cursor-pointer flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? (
                    <RotateCw className="w-4 h-4 animate-spin" />
                  ) : (
                    <span>{str('loginBtn', 'Log In', 'تسجيل الدخول')}</span>
                  )}
                </button>
              </form>

              {/* Terms & Partner Footer */}
              <div className="pt-4 border-t border-zinc-100 dark:border-zinc-800/80 space-y-3 text-center">
                <p className="text-[11px] text-zinc-400 dark:text-zinc-500 leading-relaxed max-w-xs mx-auto">
                  {str(
                    'termsNotice',
                    "By continuing, you agree to ShineCode's Terms of Service and Privacy Policy.",
                    'بالمتابعة، فإنكِ توافقين على شروط الخدمة وسياسة الخصوصية لشاين كود.'
                  )}
                </p>
                <div className="text-xs">
                  <span className="text-zinc-500 dark:text-zinc-400">
                    {str(
                      'partnerPrompt',
                      'Are you a beauty professional?',
                      'هل أنتِ متخصصة أو صاحبة صالون تجميل؟'
                    )}{' '}
                  </span>
                  <Link
                    href={`/${locale}/partner`}
                    onClick={closeAuthModal}
                    className="text-brand-600 dark:text-brand-400 font-bold hover:underline"
                  >
                    {str('joinPartnerLink', 'Join as a Partner', 'انضمي كشريك')}
                  </Link>
                </div>
              </div>
            </motion.div>
          )}

          {/* ─────────────────────────────────────────────────────────────
              STATE 2: FORGOT PASSWORD (Email Recovery Request)
             ───────────────────────────────────────────────────────────── */}
          {step === 'forgot_password' && (
            <motion.div
              key="step-forgot-password"
              initial={{ opacity: 0, x: 16 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 16 }}
              transition={{ duration: 0.2 }}
              className="space-y-6"
            >
              <ResponsiveModalHeader className="text-center sm:text-start mb-0">
                <div className="w-11 h-11 rounded-2xl bg-brand-50 dark:bg-brand-950/60 border border-brand-200 dark:border-brand-900/50 flex items-center justify-center text-brand-600 dark:text-brand-400 mb-3">
                  <KeyRound className="w-5 h-5" />
                </div>
                <ResponsiveModalTitle className="text-2xl font-extrabold text-zinc-900 dark:text-white tracking-tight">
                  {str('forgotTitle', 'Reset Password', 'استعادة كلمة المرور')}
                </ResponsiveModalTitle>
                <ResponsiveModalDescription className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                  {str(
                    'forgotSubtitle',
                    'Enter your registered email address to receive password reset instructions.',
                    'أدخلي بريدكِ الإلكتروني المسجل وسنرسل لكِ رابط الاستعادة.'
                  )}
                </ResponsiveModalDescription>
              </ResponsiveModalHeader>

              {error && (
                <div className="p-3 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-xl text-rose-700 dark:text-rose-300 text-xs font-medium">
                  {error}
                </div>
              )}

              <form onSubmit={handleForgotPasswordSubmit} className="space-y-4">
                {/* Email Field */}
                <div className="space-y-1.5">
                  <label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
                    <Mail className="w-3.5 h-3.5 text-zinc-400" />
                    <span>{str('emailLabel', 'Email Address', 'البريد الإلكتروني')} *</span>
                  </label>
                  <Input
                    id="forgot-email"
                    type="email"
                    autoFocus
                    required
                    autoComplete="email"
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value);
                      if (error) setError(null);
                    }}
                    placeholder={str('emailPlaceholder', 'you@example.com', 'example@example.com')}
                    className="h-12 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-700"
                  />
                </div>

                {/* Turnstile Captcha Widget */}
                <TurnstileWidget
                  containerId="turnstile-forgot-container"
                  onVerify={(token) => {
                    setTurnstileToken(token);
                    setIsTurnstileVerified(true);
                  }}
                  onExpire={() => {
                    setTurnstileToken('');
                    setIsTurnstileVerified(false);
                  }}
                  isVerified={isTurnstileVerified}
                  isAr={isAr}
                />

                {/* Primary Action Button */}
                <button
                  type="submit"
                  disabled={isLoading || !isTurnstileVerified}
                  className="w-full bg-brand-500 hover:bg-brand-600 active:bg-brand-700 text-white rounded-xl py-3.5 font-bold mt-4 transition-all duration-200 shadow-md hover:shadow-brand-500/25 active:scale-[0.99] cursor-pointer flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? (
                    <RotateCw className="w-4 h-4 animate-spin" />
                  ) : (
                    <span>{str('sendResetLink', 'Send Reset Link', 'إرسال رابط الاستعادة')}</span>
                  )}
                </button>

                {/* Back to Login */}
                <button
                  type="button"
                  onClick={() => switchStep('login')}
                  className="w-full text-xs font-semibold text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white py-2 flex items-center justify-center gap-1.5 transition-colors cursor-pointer"
                >
                  <ArrowLeft className="w-3.5 h-3.5 rtl:rotate-180" />
                  <span>{str('backToLogin', 'Back to Log In', 'العودة لتسجيل الدخول')}</span>
                </button>
              </form>
            </motion.div>
          )}

          {/* ─────────────────────────────────────────────────────────────
              STATE 3: FORGOT PASSWORD SUCCESS
             ───────────────────────────────────────────────────────────── */}
          {step === 'forgot_password_success' && (
            <motion.div
              key="step-forgot-success"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="flex flex-col items-center justify-center gap-4 py-8 text-center"
            >
              <div className="w-16 h-16 rounded-full bg-emerald-50 dark:bg-emerald-950/50 border border-emerald-200 dark:border-emerald-800 flex items-center justify-center">
                <CheckCircle2 className="w-8 h-8 text-emerald-600 dark:text-emerald-400" />
              </div>
              <div>
                <p className="text-xl font-extrabold text-zinc-900 dark:text-white tracking-tight">
                  {str('resetLinkSentTitle', 'Check Your Email', 'تفقد بريدكِ الإلكتروني')}
                </p>
                <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-2 max-w-xs mx-auto leading-relaxed">
                  {str(
                    'resetLinkSentDesc',
                    'We have sent a password reset link to your email address. Please follow the instructions to set your new password.',
                    'أرسلنا رابط استعادة كلمة المرور إلى بريدكِ الإلكتروني. يرجى اتباع التعليمات لتعيين كلمة مرور جديدة.'
                  )}
                </p>
              </div>

              <button
                type="button"
                onClick={() => switchStep('login')}
                className="w-full bg-brand-500 hover:bg-brand-600 active:bg-brand-700 text-white rounded-xl py-3.5 font-bold mt-4 transition-all duration-200 shadow-md hover:shadow-brand-500/25 active:scale-[0.99] cursor-pointer flex items-center justify-center gap-2"
              >
                <span>{str('backToLogin', 'Back to Log In', 'العودة لتسجيل الدخول')}</span>
              </button>
            </motion.div>
          )}

          {/* ─────────────────────────────────────────────────────────────
              STATE 4: LOGIN SUCCESS FLASH
             ───────────────────────────────────────────────────────────── */}
          {step === 'success' && (
            <motion.div
              key="step-success"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="flex flex-col items-center justify-center gap-4 py-8 text-center"
            >
              <div className="w-16 h-16 rounded-full bg-emerald-50 dark:bg-emerald-950/50 border border-emerald-200 dark:border-emerald-800 flex items-center justify-center">
                <CheckCircle2 className="w-8 h-8 text-emerald-600 dark:text-emerald-400" />
              </div>
              <div>
                <p className="text-lg font-extrabold text-zinc-900 dark:text-white tracking-tight">
                  {isAr ? 'تم تسجيل الدخول بنجاح!' : 'Logged in successfully!'}
                </p>
                <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                  {isAr ? 'جاري تحميل حسابكِ...' : 'Loading your account…'}
                </p>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </ResponsiveModalContent>
    </ResponsiveModal>
  );
}

export default AuthModal;
