'use client';

import { useState } from 'react';
import Link from 'next/link';
import { localePath, type Locale } from '@ai-radar/shared';
import type { Dictionary } from '@/lib/dictionary';

type State = 'idle' | 'working' | 'done' | 'error';

function apiBase(): string {
  return (process.env.NEXT_PUBLIC_API_BASE_URL ?? 'http://localhost:4000/api').replace(/\/+$/, '');
}

/**
 * Set a new password from a reset link.
 *
 * Client-side, unlike the verify page: this one needs a form, and the
 * token must not be spent until the reader actually submits a password.
 * Verifying on load would burn the single-use token on a preview fetch
 * by a mail client.
 */
export function ResetForm({
  token,
  locale,
  dict,
}: {
  token: string;
  locale: Locale;
  dict: Dictionary;
}) {
  const t = dict.auth;
  const [password, setPassword] = useState('');
  const [state, setState] = useState<State>('idle');
  const [error, setError] = useState<string | null>(null);

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setState('working');
    setError(null);

    try {
      const response = await fetch(`${apiBase()}/auth/reset`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ token, password }),
      });

      const body = (await response.json()) as { ok?: boolean; error?: string };

      if (!body.ok) {
        setError(body.error ?? t.resetFailedBody);
        setState('error');
        return;
      }

      setState('done');
    } catch {
      setError(t.genericError);
      setState('error');
    }
  }

  if (state === 'done') {
    return (
      <div className="token-card">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">{t.resetDoneTitle}</h1>
        <p className="token-body">{t.resetDoneBody}</p>
        <Link href={localePath('/signin', locale)} className="token-link">
          {t.signIn} →
        </Link>
      </div>
    );
  }

  if (!token) {
    return (
      <div className="token-card">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">{t.resetFailedTitle}</h1>
        <p className="token-body">{t.resetFailedBody}</p>
        <Link href={localePath('/signin', locale)} className="token-link">
          {t.signIn} →
        </Link>
      </div>
    );
  }

  return (
    <div className="auth-card">
      <h1 className="auth-title">{t.resetTitle}</h1>
      <p className="auth-blurb">{t.resetBody}</p>

      <form onSubmit={submit} noValidate>
        <label className="auth-label" htmlFor="reset-password">
          {t.newPassword}
        </label>
        <input
          id="reset-password"
          type="password"
          className="auth-input"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          autoComplete="new-password"
          required
          aria-invalid={state === 'error'}
        />

        {error && (
          <p className="auth-error" role="alert">
            {error}
          </p>
        )}

        <button
          type="submit"
          className="auth-submit"
          disabled={state === 'working' || password.length === 0}
        >
          {t.resetButton}
        </button>
      </form>
    </div>
  );
}

/**
 * Ask for a reset link.
 *
 * Always reports the same thing, because the API deliberately cannot
 * tell us whether the address exists.
 */
export function ForgotForm({ locale, dict }: { locale: Locale; dict: Dictionary }) {
  const t = dict.auth;
  const [email, setEmail] = useState('');
  const [state, setState] = useState<State>('idle');

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setState('working');

    try {
      await fetch(`${apiBase()}/auth/forgot`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email }),
      });
    } catch {
      // Deliberately ignored. A network failure and an unknown address
      // must look identical, or this becomes a membership oracle.
    }

    setState('done');
  }

  if (state === 'done') {
    return (
      <div className="token-card">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">{t.forgotSentTitle}</h1>
        <p className="token-body">{t.forgotSentBody}</p>
        <Link href={localePath('/signin', locale)} className="token-link">
          {t.signIn} →
        </Link>
      </div>
    );
  }

  return (
    <div className="auth-card">
      <h1 className="auth-title">{t.forgotTitle}</h1>
      <p className="auth-blurb">{t.forgotBody}</p>

      <form onSubmit={submit} noValidate>
        <label className="auth-label" htmlFor="forgot-email">
          {t.email}
        </label>
        <input
          id="forgot-email"
          type="email"
          className="auth-input"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          autoComplete="email"
          required
        />

        <button
          type="submit"
          className="auth-submit"
          disabled={state === 'working' || email.length === 0}
        >
          {t.forgotButton}
        </button>
      </form>

      <p className="auth-alt">
        <Link href={localePath('/signin', locale)}>{t.signIn}</Link>
      </p>
    </div>
  );
}
