'use client';

import React, { Suspense, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { motion, AnimatePresence } from 'framer-motion';
import { Star, Sparkles, Check, Eye, EyeOff, Lock, ArrowRight, Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
import LightHeaderLogo from '@/components/brand/LightHeaderLogo';
import { getApiPath } from '@/lib/basePath';
import CountryFlag from '@/components/utils/CountryFlag';
import { appendRegionCurrencyToPath } from '@/lib/regionCurrencyLink';
import { DEFAULT_SPEECH_PLAN_REGION_KEY, getSpeechPlan } from '@/lib/speechPlans';
import { getStoredLandingRegionKey } from '@/lib/landingRegionStorage';

const reviews = [
  { name: 'Priya S.', flag: '🇮🇳', band: 'IELTS 7.5', text: 'Told me exactly which phonemes to fix. Got my target band first try.' },
  { name: 'Ahmed K.', flag: '🇦🇪', band: 'IELTS 7.0', text: 'Better than any tutor I had. Instant, honest, detailed.' },
  { name: 'Maria L.', flag: '🇬🇧', band: 'CEFR C1', text: 'Tested at midnight - full report by 12:05. Unreal.' },
];
const reviewFlagCodes = ['IN', 'AE', 'GB'];
const reviewFlagLabels = ['India', 'United Arab Emirates', 'United Kingdom'];

const features = [
  'Phoneme-level pronunciation analysis',
  'IELTS, CEFR and TOEFL benchmarks',
  'Instant AI feedback and PDF report',
  'Results in under 5 minutes',
];

function ResetPasswordContent() {
  const navigate = useNavigate();
  const searchParams = useSearchParams();
  const token = searchParams.get('token') || '';
  const signinPath = appendRegionCurrencyToPath('/tools/signin');
  const starterPlan = getSpeechPlan('starter', { regionKey: getStoredLandingRegionKey(DEFAULT_SPEECH_PLAN_REGION_KEY) });

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPass, setShowPass] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (!token) {
      setError('Reset token is missing or invalid. Please request a new reset link.');
      return;
    }
    if (password.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    if (password !== confirmPassword) {
      setError('Passwords do not match.');
      return;
    }

    try {
      setLoading(true);
      const res = await fetch(getApiPath('/api/auth/reset-password'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password, confirmPassword }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.message || 'Unable to reset password. Please try again.');
        return;
      }
      setSuccessMessage(data.message || 'Your password has been reset successfully.');
      setSuccess(true);
    } catch {
      setError('Unable to reset password. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = {
    background: 'rgba(255,255,255,0.07)',
    borderColor: 'rgba(255,255,255,0.12)',
  };

  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="min-h-screen flex flex-col" style={{ background: 'linear-gradient(160deg, #150408 0%, #2A0B18 40%, #3D0F22 100%)' }}>

      {/* Dot grid */}
      <div className="fixed inset-0 pointer-events-none opacity-[0.03]"
        style={{ backgroundImage: 'radial-gradient(circle, #fff 1px, transparent 1px)', backgroundSize: '28px 28px' }} />

      {/* Gold glow */}
      <div className="fixed top-0 right-0 w-[700px] h-[500px] pointer-events-none"
        style={{ background: 'radial-gradient(ellipse at top right, rgba(212,176,56,0.15) 0%, transparent 65%)' }} />

      {/* Nav */}
      <nav className="relative z-10 flex items-center justify-between px-6 sm:px-10 py-5 border-b border-white/[0.06]">
        <button onClick={() => navigate('/tools')} className="flex items-center">
          <LightHeaderLogo className="h-9 w-auto object-contain" />
        </button>
        <button onClick={() => navigate(signinPath)}
          className="text-white/30 hover:text-white/60 text-sm font-semibold transition-colors">
          Back to sign in
        </button>
      </nav>

      {/* Main */}
      <div className="relative z-10 flex-1 flex items-center justify-center px-4 py-10">
        <div className="w-full max-w-6xl flex flex-col lg:flex-row gap-10 lg:gap-16 items-center">

          {/* Left column */}
          <div className="flex-1 max-w-lg w-full">
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}>

              <div className="inline-flex items-center gap-2 rounded-full border px-3.5 py-1.5 mb-6"
                style={{ background: 'rgba(212,176,56,0.08)', borderColor: 'rgba(212,176,56,0.25)' }}>
                <Sparkles className="w-3 h-3" style={{ color: '#D4B038' }} />
                <span className="text-[11px] font-bold uppercase tracking-widest" style={{ color: '#D4B038' }}>AI-Powered - Exam-Grade</span>
              </div>

              <h1 className="text-4xl sm:text-5xl font-black text-white leading-[1.1] mb-5 tracking-tight">
                Know your real<br />
                <span style={{ color: '#D4B038' }}>English level</span><br />
                in minutes.
              </h1>

              <p className="text-white/45 text-sm leading-relaxed mb-8">
                A full phoneme-level report with IELTS, CEFR and TOEFL benchmarks - starting at just <span className="text-white/70 font-bold">{starterPlan.price}/mo</span>.
              </p>

              <ul className="space-y-2.5 mb-10">
                {features.map((f) => (
                  <li key={f} className="flex items-center gap-3 text-sm text-white/60 font-medium">
                    <div className="w-5 h-5 rounded-full flex items-center justify-center shrink-0"
                      style={{ background: 'rgba(212,176,56,0.15)', border: '1px solid rgba(212,176,56,0.3)' }}>
                      <Check className="w-3 h-3" style={{ color: '#D4B038' }} />
                    </div>
                    {f}
                  </li>
                ))}
              </ul>

              <div className="space-y-3">
                {reviews.map((r, i) => (
                  <motion.div key={i}
                    initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.15 + i * 0.08 }}
                    className="flex items-start gap-3 rounded-2xl px-4 py-3.5"
                    style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)' }}>
                    <CountryFlag
                      code={reviewFlagCodes[i]}
                      label={reviewFlagLabels[i]}
                      className="w-6 h-4 shrink-0 mt-1"
                    />
                    <div className="min-w-0">
                      <div className="flex items-center gap-2 mb-1 flex-wrap">
                        <div className="flex gap-0.5">
                          {[...Array(5)].map((_, j) => <Star key={j} className="w-2.5 h-2.5 fill-[#D4B038] text-[#D4B038]" />)}
                        </div>
                        <span className="text-[10px] font-extrabold px-2 py-0.5 rounded-full"
                          style={{ color: '#D4B038', background: 'rgba(212,176,56,0.12)' }}>{r.band}</span>
                        <span className="text-white/25 text-[10px] font-semibold">- {r.name}</span>
                      </div>
                      <p className="text-white/45 text-xs leading-relaxed">&quot;{r.text}&quot;</p>
                    </div>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </div>

          {/* Right column */}
          <div className="w-full lg:w-[420px] shrink-0">
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}>
              <div className="rounded-3xl p-7"
                style={{
                  background: 'rgba(255,255,255,0.05)',
                  border: '1px solid rgba(255,255,255,0.1)',
                  backdropFilter: 'blur(24px)',
                  boxShadow: '0 20px 60px rgba(0,0,0,0.4)',
                }}>

                <AnimatePresence mode="wait">

                  {/* Success state */}
                  {success ? (
                    <motion.div key="success"
                      initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0 }}
                      className="text-center py-6">
                      <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-5"
                        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-2xl font-black text-white mb-2">Password updated!</h3>
                      <p className="text-white/40 text-sm mb-8 leading-relaxed">
                        {successMessage || 'Your password has been reset successfully.'}<br />You can now sign in with your new password.
                      </p>
                      <button
                        onClick={() => navigate(signinPath)}
                        className="w-full py-3.5 rounded-xl font-extrabold text-sm flex items-center justify-center gap-2 transition-all hover:opacity-90"
                        style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22' }}>
                        <Lock className="w-4 h-4" /> Sign In Now <ArrowRight className="w-4 h-4" />
                      </button>
                    </motion.div>

                  ) : (

                    /* Reset form */
                    <motion.div key="form" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>

                      {/* Header */}
                      <div className="mb-6">
                        <div className="w-11 h-11 rounded-2xl flex items-center justify-center mb-4"
                          style={{ background: 'rgba(212,176,56,0.12)', border: '1px solid rgba(212,176,56,0.2)' }}>
                          <Lock className="w-5 h-5" style={{ color: '#D4B038' }} />
                        </div>
                        <h3 className="text-2xl font-black text-white mb-1">Reset your password</h3>
                        <p className="text-white/40 text-sm">Choose a strong new password for your account.</p>
                      </div>

                      {!token && (
                        <div className="flex items-center gap-2 text-amber-300 text-xs font-semibold rounded-xl px-3 py-2.5 mb-4"
                          style={{ background: 'rgba(245,158,11,0.12)', border: '1px solid rgba(245,158,11,0.25)' }}>
                          <AlertCircle className="w-4 h-4 flex-shrink-0" /> Missing or invalid reset token.
                        </div>
                      )}

                      <form onSubmit={handleSubmit} className="space-y-4">

                        {/* New password */}
                        <div>
                          <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">
                            New Password
                          </label>
                          <div className="relative">
                            <input
                              type={showPass ? 'text' : 'password'}
                              required
                              placeholder="Min. 8 characters"
                              value={password}
                              onChange={e => setPassword(e.target.value)}
                              className={`${inputClass} pr-11`}
                              style={inputStyle}
                            />
                            <button type="button" onClick={() => setShowPass(v => !v)}
                              className="absolute right-3 top-1/2 -translate-y-1/2 text-white/30 hover:text-white/60 transition-colors">
                              {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                            </button>
                          </div>
                        </div>

                        {/* Confirm password */}
                        <div>
                          <label className="text-xs font-bold text-white/40 uppercase tracking-wide mb-1.5 block">
                            Confirm New Password
                          </label>
                          <div className="relative">
                            <input
                              type={showConfirm ? 'text' : 'password'}
                              required
                              placeholder="Repeat your password"
                              value={confirmPassword}
                              onChange={e => setConfirmPassword(e.target.value)}
                              className={`${inputClass} pr-11`}
                              style={inputStyle}
                            />
                            <button type="button" onClick={() => setShowConfirm(v => !v)}
                              className="absolute right-3 top-1/2 -translate-y-1/2 text-white/30 hover:text-white/60 transition-colors">
                              {showConfirm ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                            </button>
                          </div>
                        </div>

                        {/* Error */}
                        {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>
                        )}

                        {/* Submit */}
                        <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 hover:opacity-90 disabled:opacity-60 mt-2"
                          style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22' }}>
                          {loading
                            ? <Loader2 className="w-4 h-4 animate-spin" />
                            : <><Lock className="w-4 h-4" /> Set New Password <ArrowRight className="w-4 h-4" /></>
                          }
                        </button>
                      </form>

                      {/* Back link */}
                      <div className="text-center mt-5">
                        <button onClick={() => navigate(signinPath)}
                          className="text-xs text-white/30 hover:text-white/60 font-semibold transition-colors">
                          Back to sign in
                        </button>
                      </div>

                    </motion.div>
                  )}

                </AnimatePresence>
              </div>
            </motion.div>
          </div>

        </div>
      </div>

      {/* Footer */}
      <div className="relative z-10 border-t border-white/[0.05] py-4 px-6 text-center">
        <p className="text-white/15 text-xs">© 2026 Cambridge Veritas · Not affiliated with Cambridge Assessment English</p>
      </div>
    </div>
  );
}

function ResetPasswordFallback() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-[#150408]">
      <div className="w-8 h-8 border-4 border-white/10 border-t-[#D4B038] rounded-full animate-spin" />
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={<ResetPasswordFallback />}>
      <ResetPasswordContent />
    </Suspense>
  );
}
