'use client';

import { useState, useEffect, useRef, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Mail, AlertCircle, Loader2, RefreshCw } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';
import { useAuth } from '@client/contexts/AuthContext';

function VerifyEmailInner() {
  const router = useRouter();
  const params = useSearchParams();
  const email = params.get('email') || '';
  const { t } = useLanguage();
  const auth = useAuth();
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [error, setError] = useState('');
  const [info, setInfo] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!email) router.replace('/register');
    inputRef.current?.focus();
  }, [email, router]);

  useEffect(() => {
    if (cooldown <= 0) return;
    const t = setInterval(() => setCooldown(s => s - 1), 1000);
    return () => clearInterval(t);
  }, [cooldown]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!/^\d{6}$/.test(code.trim())) { setError(t('verify.invalidCode', 'Enter the 6-digit code from your email')); return; }
    setLoading(true); setError(''); setInfo('');
    try {
      const res = await fetch('/api/auth/verify-otp', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code: code.trim() }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Verification failed');
      // Refresh auth context, then onboard
      await auth.getCurrentUser();
      window.location.href = '/onboarding';
    } catch (err: any) {
      setError(err?.message || t('verify.failed', 'Verification failed. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    if (cooldown > 0) return;
    setResending(true); setError(''); setInfo('');
    try {
      const res = await fetch('/api/auth/resend-otp', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Could not resend code');
      setInfo(data.throttled
        ? t('verify.alreadySent', 'A code was just sent — check your inbox.')
        : t('verify.resent', 'A new code is on its way.'));
      setCooldown(60);
    } catch (err: any) {
      setError(err?.message || 'Failed to resend');
    } finally {
      setResending(false);
    }
  };

  return (
    <div className="min-h-screen flex items-start justify-center py-16 px-4" style={{ backgroundColor: 'hsl(var(--background))' }}>
      <div className="w-full max-w-md">
        <div className="card p-8">
          <div className="w-12 h-12 rounded-2xl flex items-center justify-center mb-5" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
            <Mail size={22} style={{ color: 'hsl(var(--primary))' }} />
          </div>
          <h1 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>
            {t('verify.title', 'Verify your email')}
          </h1>
          <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('verify.sentTo', 'We sent a 6-digit code to')} <strong>{email}</strong>. {t('verify.expiresIn', 'It expires in 10 minutes.')}
          </p>

          {error && (
            <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
              <AlertCircle size={15} />{error}
            </div>
          )}
          {info && (
            <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(142, 71%, 95%)', color: 'hsl(142, 71%, 30%)', border: '1px solid hsl(142, 71%, 85%)' }}>
              {info}
            </div>
          )}

          <form onSubmit={submit} className="space-y-4">
            <input
              ref={inputRef}
              className="input-base text-center text-2xl font-bold tracking-[0.5em]"
              maxLength={6}
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="••••••"
              value={code}
              onChange={e => setCode(e.target.value.replace(/\D/g, ''))}
            />
            <button type="submit" className="btn-primary w-full" disabled={loading || !/^\d{6}$/.test(code.trim())}>
              {loading ? <Loader2 size={16} className="animate-spin" /> : t('verify.button', 'Verify & continue')}
            </button>
          </form>

          <div className="mt-5 text-sm text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('verify.didntReceive', "Didn't get the code?")}{' '}
            <button type="button" onClick={resend} disabled={resending || cooldown > 0} className="font-semibold inline-flex items-center gap-1 disabled:opacity-50" style={{ color: 'hsl(var(--primary))' }}>
              {resending && <Loader2 size={12} className="animate-spin" />}
              {!resending && <RefreshCw size={12} />}
              {cooldown > 0 ? `${t('verify.resendIn', 'Resend in')} ${cooldown}s` : t('verify.resend', 'Resend code')}
            </button>
          </div>

          <div className="mt-6 pt-6 border-t text-center text-sm" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--muted-foreground))' }}>
            <Link href="/register" className="font-semibold" style={{ color: 'hsl(var(--primary))' }}>
              ← {t('verify.changeEmail', 'Change email')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function VerifyEmailPage() {
  return (
    <Suspense fallback={<div className="min-h-screen" />}>
      <VerifyEmailInner />
    </Suspense>
  );
}
