'use client';

import { useCallback, useEffect, useState } from 'react';
import { adminGet, adminPost, AdminError } from '@/lib/admin-api';

const TABS = [
  { key: 'overview', label: 'Overview' },
  { key: 'published', label: 'Published' },
  { key: 'held', label: 'Held' },
  { key: 'rejected', label: 'Why not published' },
  { key: 'sources', label: 'Sources' },
  { key: 'runs', label: 'Runs' },
  { key: 'audience', label: 'Audience' },
  { key: 'ads', label: 'Ads' },
] as const;

export type TabKey = (typeof TABS)[number]['key'];

/**
 * Auth wrapper and tab chrome for the admin.
 *
 * A client component because the session lives in an HttpOnly cookie the
 * browser sends, and the admin is interactive throughout — there is no
 * SEO reason to render any of it on the server.
 */
export function AdminShell({
  children,
  tab,
  onTab,
}: {
  children: React.ReactNode;
  tab: TabKey;
  onTab: (tab: TabKey) => void;
}) {
  const [state, setState] = useState<'checking' | 'in' | 'out'>('checking');

  useEffect(() => {
    adminGet('/admin/session')
      .then(() => setState('in'))
      .catch(() => setState('out'));
  }, []);

  if (state === 'checking') {
    return (
      <div className="login-wrap">
        <p className="admin-empty">Checking session…</p>
      </div>
    );
  }

  if (state === 'out') {
    return <Login onSuccess={() => setState('in')} />;
  }

  return (
    <div className="admin-shell">
      <header className="admin-head">
        <div>
          <h1 className="admin-title">AI Radar Admin</h1>
          <p className="cell-sub">Operator console</p>
        </div>
        <div className="btn-row">
          <a href="/en" className="btn" target="_blank" rel="noreferrer">
            View site ↗
          </a>
          <button
            type="button"
            className="btn"
            onClick={async () => {
              await adminPost('/admin/logout');
              setState('out');
            }}
          >
            Sign out
          </button>
        </div>
      </header>

      <nav className="admin-nav">
        {TABS.map((t) => (
          <button
            key={t.key}
            type="button"
            className="admin-tab"
            aria-current={tab === t.key ? 'page' : undefined}
            onClick={() => onTab(t.key)}
          >
            {t.label}
          </button>
        ))}
      </nav>

      {children}
    </div>
  );
}

function Login({ onSuccess }: { onSuccess: () => void }) {
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = useCallback(
    async (event: React.FormEvent) => {
      event.preventDefault();
      setBusy(true);
      setError(null);
      try {
        await adminPost('/admin/login', { password });
        onSuccess();
      } catch (err) {
        setError(
          err instanceof AdminError && err.status === 401
            ? 'Wrong password.'
            : 'Could not reach the API. Is it running?',
        );
      } finally {
        setBusy(false);
      }
    },
    [password, onSuccess],
  );

  return (
    <div className="login-wrap">
      <form className="login-card" onSubmit={submit}>
        <h1 className="admin-title">AI Radar Admin</h1>
        <p className="cell-sub">Sign in to continue</p>

        <input
          id="admin-password"
          type="password"
          className="login-input"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
          autoComplete="current-password"
          autoFocus
        />

        {error && <p className="login-error">{error}</p>}

        <button
          type="submit"
          className="btn primary"
          disabled={busy || password.length === 0}
          style={{ marginTop: 'var(--s4)', width: '100%' }}
        >
          {busy ? 'Signing in…' : 'Sign in'}
        </button>
      </form>
    </div>
  );
}

export { TABS };
