'use client';

/**
 * Authentication configuration — UI-driven auth mode + Supabase credentials.
 * Writes through POST /api/auth/config (no env editing, no restart). Switching
 * to Supabase requires a passing connection test (anti-lockout, enforced
 * server-side too).
 */

import { useState } from 'react';

export default function AuthConfigForm({ initial }) {
  const [mode, setMode] = useState(initial?.mode || 'local');
  const [url, setUrl] = useState(initial?.url || '');
  const [anonKey, setAnonKey] = useState(initial?.anonKey || '');
  const [serviceKey, setServiceKey] = useState('');
  const [testing, setTesting] = useState(false);
  const [saving, setSaving] = useState(false);
  const [banner, setBanner] = useState(null); // { tone: 'ok'|'err'|'info', text }

  const envLocked = Boolean(initial?.envLocked);
  const serviceKeySet = Boolean(initial?.serviceKeySet);
  const wasSupabase = initial?.mode === 'supabase';

  async function postConfig(payload) {
    const res = await fetch('/api/auth/config', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(payload),
    });
    const data = await res.json().catch(() => ({}));
    return { status: res.status, data };
  }

  async function onTest() {
    setBanner(null);
    setTesting(true);
    try {
      const { status, data } = await postConfig({ action: 'test', url, anonKey });
      if (data.ok) {
        setBanner({ tone: 'ok', text: 'Connection succeeded — Supabase project is reachable.' });
      } else if (status === 403) {
        setBanner({
          tone: 'err',
          text: 'Not authorized — your session did not resolve as an owner/admin (this is not a connectivity problem). Reload after signing in, or reset to local mode using the recovery token in data/.auth-recovery-token.',
        });
      } else if (data.test?.error) {
        setBanner({ tone: 'err', text: `Connection failed: ${data.test.error}.` });
      } else {
        setBanner({ tone: 'err', text: `Connection test failed: ${data.error || 'unknown error'}.` });
      }
    } catch {
      setBanner({ tone: 'err', text: 'Could not reach the server to run the test.' });
    } finally {
      setTesting(false);
    }
  }

  async function onSave() {
    setBanner(null);
    setSaving(true);
    try {
      const payload = { action: 'save', mode };
      if (url) payload.url = url;
      if (anonKey) payload.anonKey = anonKey;
      if (serviceKey) payload.serviceKey = serviceKey;

      const { status, data } = await postConfig(payload);

      if (status === 422) {
        setBanner({ tone: 'err', text: `Cannot switch to Supabase — connection test failed: ${data.test?.error || 'unreachable'}. Fix the URL/anon key and try again.` });
        return;
      }
      if (status === 403) {
        setBanner({ tone: 'err', text: 'Not allowed — you must be an owner or admin to change auth settings.' });
        return;
      }
      if (!data.ok) {
        setBanner({ tone: 'err', text: `Save failed: ${data.error || 'unknown error'}.` });
        return;
      }

      // Mode actually switched to supabase → app is now gated; go sign in.
      if (mode === 'supabase' && !wasSupabase) {
        setBanner({ tone: 'info', text: 'Saved. Supabase mode enabled — redirecting to sign in…' });
        setTimeout(() => window.location.assign('/login'), 800);
        return;
      }
      setBanner({ tone: 'ok', text: 'Authentication settings saved.' });
      setTimeout(() => window.location.reload(), 700);
    } catch {
      setBanner({ tone: 'err', text: 'Could not reach the server to save.' });
    } finally {
      setSaving(false);
    }
  }

  const bannerStyle = {
    ok: { background: 'rgba(34,139,84,.10)', color: '#1d7a47', border: '1px solid rgba(34,139,84,.25)' },
    err: { background: 'rgba(194,69,42,.08)', color: '#a8331c', border: '1px solid rgba(194,69,42,.22)' },
    info: { background: 'rgba(20,22,26,.05)', color: '#3a3f47', border: '1px solid rgba(20,22,26,.12)' },
  };

  return (
    <div className="auth-config-form" style={{ display: 'grid', gap: '0.85rem' }}>
      {/* Mode selector */}
      <div className="auth-mode-toggle" role="radiogroup" aria-label="Authentication mode">
        <button
          type="button"
          role="radio"
          aria-checked={mode === 'local'}
          className={mode === 'local' ? 'active' : ''}
          onClick={() => !envLocked && setMode('local')}
          disabled={envLocked}
        >
          Local operator
          <small>Single owner, no sign-in. Default.</small>
        </button>
        <button
          type="button"
          role="radio"
          aria-checked={mode === 'supabase'}
          className={mode === 'supabase' ? 'active' : ''}
          onClick={() => !envLocked && setMode('supabase')}
          disabled={envLocked}
        >
          Supabase accounts
          <small>Real sign-in, orgs, cloud sync.</small>
        </button>
      </div>

      {envLocked ? (
        <p className="admin-muted" style={{ fontSize: '0.82em' }}>
          Auth mode is locked by the <code>MADARX_AUTH_MODE</code> environment variable. Unset it to manage the mode here.
        </p>
      ) : null}

      {/* Supabase credentials */}
      <div className="admin-form-row" style={{ display: 'grid', gap: '0.75rem' }}>
        <label className="admin-field">
          <span>Supabase project URL</span>
          <input
            type="url"
            className="admin-input"
            placeholder="https://YOUR-PROJECT.supabase.co"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            autoComplete="off"
          />
        </label>
        <label className="admin-field">
          <span>Anon (public) key</span>
          <input
            type="text"
            className="admin-input"
            placeholder="eyJhbGciOi…"
            value={anonKey}
            onChange={(e) => setAnonKey(e.target.value)}
            autoComplete="off"
          />
        </label>
        <label className="admin-field">
          <span>Service-role key {serviceKeySet ? <em style={{ color: '#1d7a47', fontStyle: 'normal' }}>· set</em> : null}</span>
          <input
            type="password"
            className="admin-input"
            placeholder={serviceKeySet ? '•••••••• (leave blank to keep)' : 'eyJhbGciOi… (enables cloud sync)'}
            value={serviceKey}
            onChange={(e) => setServiceKey(e.target.value)}
            autoComplete="off"
          />
        </label>
        <p className="admin-muted" style={{ fontSize: '0.78em', margin: 0 }}>
          Stored encrypted in the local secrets vault. The service-role key never leaves the server and powers cloud sync and shared spaces.
        </p>
        <p className="admin-muted" style={{ fontSize: '0.78em', margin: 0 }}>
          Lockout safety: if Supabase sign-in ever fails, reset to local mode from the login page using the recovery token in <code>data/.auth-recovery-token</code>, or set <code>MADARX_AUTH_MODE=local</code> in the environment.
        </p>
      </div>

      {banner ? (
        <div style={{ ...bannerStyle[banner.tone], padding: '0.6rem 0.8rem', borderRadius: 10, fontSize: '0.85em' }}>
          {banner.text}
        </div>
      ) : null}

      <div className="admin-form-actions" style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
        <button type="button" className="admin-btn-sm" onClick={onTest} disabled={testing || saving || !url || !anonKey}>
          {testing ? 'Testing…' : 'Test connection'}
        </button>
        <button type="button" className="admin-btn-primary" onClick={onSave} disabled={saving || testing || envLocked}>
          {saving ? 'Saving…' : mode === 'supabase' && !wasSupabase ? 'Save & switch to Supabase' : 'Save settings'}
        </button>
      </div>
    </div>
  );
}
