'use client';

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

interface Preferences {
  email: string;
  locale: string;
  status: string;
  wantsDigest: boolean;
  wantsInstant: boolean;
  instantThreshold: number;
}

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

/**
 * Preference management, reached from the footer of every email.
 *
 * The token in the URL is the only credential. That is acceptable here
 * because it grants nothing beyond changing what this one address
 * receives, and because requiring a password for a newsletter would be
 * friction nobody accepts.
 */
export function PreferencesForm({ token }: { token: string | null }) {
  const [prefs, setPrefs] = useState<Preferences | null>(null);
  const [state, setState] = useState<'loading' | 'ready' | 'missing'>('loading');
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!token) {
      setState('missing');
      return;
    }

    fetch(`${apiBase()}/subscribe/preferences?t=${encodeURIComponent(token)}`)
      .then((r) => r.json())
      .then((body: { ok?: boolean } & Partial<Preferences>) => {
        if (body.ok && body.email) {
          setPrefs(body as Preferences);
          setState('ready');
        } else {
          setState('missing');
        }
      })
      .catch(() => setState('missing'));
  }, [token]);

  const locale: Locale =
    prefs?.locale && isLocale(prefs.locale) ? prefs.locale : DEFAULT_LOCALE;
  const dict = getDictionary(locale);
  const dir = locale === 'ar' ? 'rtl' : 'ltr';

  async function save(next: Partial<Preferences>) {
    if (!token || !prefs) return;

    const updated = { ...prefs, ...next };
    setPrefs(updated);
    setBusy(true);
    setSaved(false);

    try {
      await fetch(`${apiBase()}/subscribe/preferences`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          token,
          wantsDigest: updated.wantsDigest,
          wantsInstant: updated.wantsInstant,
          threshold: updated.instantThreshold,
        }),
      });
      setSaved(true);
    } finally {
      setBusy(false);
    }
  }

  if (state === 'loading') {
    return (
      <main className="page token-page">
        <div className="token-card">
          <p className="token-body">…</p>
        </div>
      </main>
    );
  }

  if (state === 'missing' || !prefs) {
    const fallback = getDictionary(DEFAULT_LOCALE);
    return (
      <main className="page token-page">
        <div className="token-card">
          <p className="token-brand">AI RADAR</p>
          <h1 className="token-title">{fallback.subscribe.unsubscribeFailedTitle}</h1>
          <p className="token-body">{fallback.subscribe.confirmFailedBody}</p>
          <Link href={localePath('/', DEFAULT_LOCALE)} className="token-link">
            {fallback.subscribe.backHome} →
          </Link>
        </div>
      </main>
    );
  }

  return (
    <main id="main" className="page token-page" dir={dir} lang={locale}>
      <div className="token-card wide">
        <p className="token-brand">AI RADAR</p>
        <h1 className="token-title">{dict.subscribe.preferencesTitle}</h1>
        <p className="token-email">{prefs.email}</p>

        <div className="pref-list">
          <label className="pref-row">
            <input
              id="pref-digest"
              type="checkbox"
              checked={prefs.wantsDigest}
              onChange={(e) => void save({ wantsDigest: e.target.checked })}
              disabled={busy}
            />
            <span>
              <strong>{dict.subscribe.wantsDigest}</strong>
              <span className="pref-help">{dict.subscribe.wantsDigestHelp}</span>
            </span>
          </label>

          <label className="pref-row">
            <input
              id="pref-instant"
              type="checkbox"
              checked={prefs.wantsInstant}
              onChange={(e) => void save({ wantsInstant: e.target.checked })}
              disabled={busy}
            />
            <span>
              <strong>{dict.subscribe.wantsInstant}</strong>
              <span className="pref-help">{dict.subscribe.wantsInstantHelp}</span>
            </span>
          </label>

          {/* Only meaningful when instant alerts are on. */}
          {prefs.wantsInstant && (
            <div className="pref-row threshold">
              <span>
                <strong>
                  {dict.subscribe.threshold} {prefs.instantThreshold}
                </strong>
                <span className="pref-help">{dict.subscribe.thresholdHelp}</span>
              </span>
              <input
                id="pref-threshold"
                type="range"
                min={50}
                max={95}
                step={5}
                value={prefs.instantThreshold}
                onChange={(e) => void save({ instantThreshold: Number(e.target.value) })}
                disabled={busy}
              />
            </div>
          )}
        </div>

        {saved && <p className="pref-saved">{dict.subscribe.saved}</p>}

        <div className="pref-footer">
          <a href={`/unsubscribe?t=${encodeURIComponent(token ?? '')}`} className="pref-unsub">
            {dict.subscribe.unsubscribeLink}
          </a>
          <Link href={localePath('/', locale)} className="token-link">
            {dict.subscribe.backHome} →
          </Link>
        </div>
      </div>
    </main>
  );
}
