'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowRight, Mail, CheckCircle2, Loader2 } from 'lucide-react';
import { getApiPath } from '@/lib/basePath';
import { isAlgebraPath } from '@/lib/authNavigation';
import { useAuth } from '@/lib/AuthContext';
import styles from './Verification.module.css';

const BRAND = '#4A1429';
const MUTED = '#6B5D52';
const BORDER = '#E5DDD5';
const CREAM = '#FAF5F0';

function getVerifySource() {
  if (typeof window === 'undefined') return { page: '/register/verify', path: '/register/verify' };

  return {
    page: window.location.pathname || '/register/verify',
    path: `${window.location.pathname || '/register/verify'}${window.location.search || ''}`,
    pageUrl: window.location.href,
    stage: 'registration_otp_verified',
  };
}

async function readJson(response) {
  const text = await response.text();
  if (!text) return {};

  try {
    return JSON.parse(text);
  } catch {
    return {};
  }
}

export default function RegisterVerifyClient({ initialEmail = '', redirectTo = '/', embedded = false }) {
  const algebra = isAlgebraPath(redirectTo);
  const router = useRouter();
  const auth = useAuth();
  const [email, setEmail] = useState(initialEmail);
  const [otp, setOtp] = useState('');
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('');
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);

  useEffect(() => {
    if (initialEmail || typeof window === 'undefined') return;
    setEmail(window.sessionStorage.getItem('register_otp_email') || '');
  }, [initialEmail]);

  async function handleVerify(event) {
    event.preventDefault();
    setError('');
    setNotice('');

    if (!email.trim()) {
      setError('Email is required.');
      return;
    }

    if (!/^\d{6}$/.test(otp.trim())) {
      setError('Enter the 6-digit verification code.');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(getApiPath('/api/auth/verify-otp'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(),
          otp: otp.trim(),
          source: getVerifySource(),
        }),
      });
      const data = await readJson(response);

      if (!response.ok) {
        throw new Error(data?.message || 'Could not verify the code.');
      }

      if (data?.user) {
        auth?.login?.(data.user);
      }

      if (typeof window !== 'undefined') {
        window.sessionStorage.removeItem('register_otp_email');
      }

      router.push(redirectTo);
      router.refresh();
    } catch (err) {
      setError(err?.message || 'Could not verify the code.');
    } finally {
      setLoading(false);
    }
  }

  async function handleResend() {
    setError('');
    setNotice('');

    if (!email.trim()) {
      setError('Email is required.');
      return;
    }

    setResending(true);
    try {
      const response = await fetch(getApiPath('/api/auth/resend-otp'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      const data = await readJson(response);

      if (!response.ok) {
        throw new Error(data?.message || 'Could not resend the code.');
      }

      setNotice(data?.message || 'Verification code sent.');
    } catch (err) {
      setError(err?.message || 'Could not resend the code.');
    } finally {
      setResending(false);
    }
  }

  return (
    <main className={`flex items-start justify-center px-4 py-10 sm:py-12 ${algebra ? styles.page : ''}`} style={{ backgroundColor: CREAM }}>
      <section className={`w-full max-w-xl rounded-3xl border bg-white p-6 shadow-xl sm:p-8 ${algebra ? styles.card : ''}`} style={{ borderColor: BORDER }}>
        {algebra && <>
          <Link href="/algebra-1/resources" className={styles.brand}><span>CV</span><div>Cambridge Veritas<small>ALGEBRA I LEARNING SPACE</small></div></Link>
          <ol className={styles.steps} aria-label="Account setup progress">
            <li><CheckCircle2 size={15} aria-hidden="true"/>Register</li>
            <li aria-current="step"><span>2</span>Verify email</li>
            <li><span>3</span>Choose grade</li>
          </ol>
        </>}
        <div className={`${algebra ? styles.icon : ''} mb-6 flex h-12 w-12 items-center justify-center rounded-xl bg-[#D4B038]/20`}>
          <Mail className="h-6 w-6" style={{ color: BRAND }} />
        </div>

        <h1 className="text-3xl font-black" style={{ color: BRAND }}>{algebra ? 'Check your inbox' : 'Verify your email'}</h1>
        <p className="mt-2 text-sm font-medium leading-6" style={{ color: MUTED }}>
          Enter the 6-digit code sent to your email address.
        </p>

        {error ? (
          <div
            role="alert"
            className="mt-5 rounded-xl border px-4 py-3 text-sm font-medium"
            style={{ backgroundColor: 'rgba(220,38,38,0.06)', borderColor: 'rgba(220,38,38,0.20)', color: '#b91c1c' }}
          >
            {error}
          </div>
        ) : null}

        {notice ? (
          <div role="status"
            className="mt-5 rounded-xl border px-4 py-3 text-sm font-medium"
            style={{ backgroundColor: 'rgba(22,163,74,0.08)', borderColor: 'rgba(22,163,74,0.20)', color: '#166534' }}
          >
            {notice}
          </div>
        ) : null}

        <form onSubmit={handleVerify} className="mt-6 space-y-4">
          <div>
            <label htmlFor="verify-email" className="mb-1.5 block text-xs font-bold uppercase tracking-wider" style={{ color: MUTED }}>Email address</label>
            <input
              id="verify-email"
              type="email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              required
              autoComplete="email"
              className="w-full rounded-xl border px-4 py-3 text-sm focus:outline-none"
              style={{ borderColor: BORDER, color: BRAND }}
            />
          </div>

          <div>
            <label htmlFor="verify-code" className="mb-1.5 block text-xs font-bold uppercase tracking-wider" style={{ color: MUTED }}>6-digit verification code</label>
            <input
              id="verify-code"
              autoComplete="one-time-code"
              pattern="[0-9]{6}"
              aria-describedby="verify-code-help"
              placeholder="000000"
              type="text"
              value={otp}
              onChange={(event) => setOtp(event.target.value.replace(/\D/g, '').slice(0, 6))}
              required
              inputMode="numeric"
              maxLength={6}
              className="w-full rounded-xl border px-4 py-3 text-center text-lg font-black tracking-[0.35em] focus:outline-none"
              style={{ borderColor: BORDER, color: BRAND }}
            />
          </div>

          <p id="verify-code-help" className={algebra ? styles.help : 'text-xs'}>Check your spam or junk folder if you don't see the email.</p>
          <button
            type="submit"
            disabled={loading || resending}
            className="flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-black text-white transition-all disabled:opacity-50"
            style={{ backgroundColor: BRAND }}
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
            {loading ? 'Verifying?' : algebra ? 'Verify & continue' : 'Verify account'}
            {!loading && <ArrowRight size={16} aria-hidden="true"/>}
          </button>
        </form>

        <div className="mt-6 flex flex-col items-center justify-between gap-3 text-sm font-medium sm:flex-row">
          <button
            type="button"
            onClick={handleResend}
            disabled={resending || loading}
            className="font-bold hover:opacity-70 disabled:opacity-50"
            style={{ color: BRAND }}
          >
            {resending ? 'Sending code...' : 'Resend code'}
          </button>
          <Link
            href={`${isAlgebraPath(redirectTo) ? '/algebra-register' : '/register'}?${new URLSearchParams({
              ...(redirectTo !== '/' ? { redirect: redirectTo } : {}),
              ...(embedded ? { embed: '1' } : {}),
            }).toString()}`}
            className="hover:opacity-70"
            style={{ color: MUTED }}
          >
            Back to registration
          </Link>
        </div>
      </section>
    </main>
  );
}
