"use client";
import { useEffect, useState } from 'react';

// Voice config section. Uses the dashboard's existing .config-* classes so
// it visually matches the Tools / WhatsApp tabs (instead of looking like a
// raw HTML form). Persists to the same localStorage keys the voice panel
// reads on mount, and broadcasts a storage event so a live panel re-reads
// settings immediately.

const REALTIME_VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse', 'marin', 'cedar'];
const REALTIME_MODELS = [
  { id: 'gpt-realtime-2', label: 'gpt-realtime-2 — most capable' },
  { id: 'gpt-realtime', label: 'gpt-realtime — standard GA' },
  { id: 'gpt-realtime-mini', label: 'gpt-realtime-mini — cost-efficient' },
];
const SPEAKING_STYLES = [
  { id: 'natural', label: 'Natural — conversational human', hint: 'Contractions, short sentences, casual acknowledgments. Closest to a friend talking.' },
  { id: 'warm',    label: 'Warm — friendly + personable',    hint: 'Softer phrasing, slight empathy markers. Good for everyday companion use.' },
  { id: 'concise', label: 'Concise — minimal words',         hint: 'Bare-minimum, direct. No filler. Best when you want answers fast.' },
  { id: 'formal',  label: 'Formal — professional briefing',  hint: 'Clean sentences, no fillers, executive tone. For meetings or read-aloud reports.' },
];

const PROVIDERS_CACHE_KEY = 'madarx:voice-providers-cache';

function load(key, fallback) {
  if (typeof window === 'undefined') return fallback;
  try { return window.localStorage.getItem(key) || fallback; } catch { return fallback; }
}
function persist(key, value) {
  if (typeof window === 'undefined') return;
  try {
    window.localStorage.setItem(key, value);
    window.dispatchEvent(new StorageEvent('storage', { key, newValue: value }));
  } catch {}
}
function loadCachedProviders() {
  if (typeof window === 'undefined') return null;
  try {
    const raw = window.localStorage.getItem(PROVIDERS_CACHE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === 'object' ? parsed : null;
  } catch { return null; }
}
function persistCachedProviders(data) {
  if (typeof window === 'undefined') return;
  try { window.localStorage.setItem(PROVIDERS_CACHE_KEY, JSON.stringify(data)); } catch {}
}

export default function VoiceConfigSection() {
  const [providers, setProviders] = useState(() => loadCachedProviders());
  const [revalidating, setRevalidating] = useState(true);
  const [mode, setMode] = useState(() => load('madarx:voice-mode', 'realtime'));
  const [ttsProvider, setTtsProvider] = useState(() => load('madarx:tts-provider', 'openai'));
  const [ttsVoice, setTtsVoice] = useState(() => load('madarx:tts-voice', ''));
  const [realtimeModel, setRealtimeModel] = useState(() => load('madarx:realtime-model', 'gpt-realtime-2'));
  const [realtimeVoice, setRealtimeVoice] = useState(() => load('madarx:realtime-voice', 'alloy'));
  const [speakingStyle, setSpeakingStyle] = useState(() => load('madarx:speaking-style', 'natural'));

  useEffect(() => {
    let cancelled = false;
    setRevalidating(true);
    fetch('/api/voice/providers')
      .then(r => r.json())
      .then(data => {
        if (cancelled) return;
        setProviders(data);
        persistCachedProviders(data);
        setRevalidating(false);
      })
      .catch(() => { if (!cancelled) setRevalidating(false); });
    return () => { cancelled = true; };
  }, []);

  const hasCaps = Boolean(providers);
  const caps = providers?.capabilities || {};
  // Before caps load, render options as enabled (optimistic) so the form is
  // usable instantly. Disabled-states snap in once the fetch resolves.
  const realtimeAvailable = hasCaps ? Boolean(caps?.realtime?.openai) : true;
  const ttsAvailable = hasCaps ? Boolean(caps?.tts?.openai || caps?.tts?.elevenlabs || caps?.tts?.local) : true;
  const localAvailable = hasCaps ? Boolean(caps?.stt?.local && caps?.tts?.local) : false;
  const capOpenaiTts = hasCaps ? Boolean(caps?.tts?.openai) : true;
  const capElevenlabsTts = hasCaps ? Boolean(caps?.tts?.elevenlabs) : true;
  const capLocalTts = hasCaps ? Boolean(caps?.tts?.local) : false;

  const update = (setter, key) => (value) => {
    setter(value);
    persist(key, String(value || ''));
  };

  return (
    <div className="config-secrets-panel voice-config">
      <div className="config-secrets-head">
        <div>
          <span className="config-section-title">Voice console</span>
          <small className="voice-config-sub">Choose how Jarvis speaks and listens. Each setting saves immediately.</small>
        </div>
      </div>

      {/* Provider readiness — chip row */}
      <section className="voice-config-section">
        <span className="voice-config-section-label">
          Provider readiness{revalidating && hasCaps ? ' · refreshing…' : ''}
        </span>
        <div className="voice-config-readiness" aria-busy={!hasCaps}>
          <CapBadge label="OpenAI realtime" on={hasCaps && Boolean(caps?.realtime?.openai)} pending={!hasCaps} />
          <CapBadge label="OpenAI TTS" on={hasCaps && Boolean(caps?.tts?.openai)} pending={!hasCaps} />
          <CapBadge label="ElevenLabs TTS" on={hasCaps && Boolean(caps?.tts?.elevenlabs)} pending={!hasCaps} />
          <CapBadge label="Anthropic stream" on={hasCaps && Boolean(caps?.llm?.anthropic)} pending={!hasCaps} />
          <CapBadge label="Local TTS/STT" on={hasCaps && localAvailable} pending={!hasCaps} />
        </div>
        {hasCaps && !realtimeAvailable && !ttsAvailable && (
          <p className="voice-config-warn">
            No voice providers configured. Add <code>OPENAI_API_KEY</code> or <code>ELEVENLABS_API_KEY</code> in <b>Tools → Secrets</b>.
          </p>
        )}
      </section>

      {/* Default mode */}
          <section className="voice-config-section">
            <span className="voice-config-section-label">Default mode</span>
            <p className="voice-config-help">What the voice console opens to.</p>
            <div className="voice-config-grid voice-config-grid--one">
              <select
                className="voice-config-select"
                value={mode}
                onChange={e => update(setMode, 'madarx:voice-mode')(e.target.value)}
              >
                <option value="realtime" disabled={!realtimeAvailable}>Live — realtime conversation{realtimeAvailable ? '' : ' (no key)'}</option>
                <option value="tts" disabled={!ttsAvailable}>Speak replies — TTS{ttsAvailable ? '' : ' (no key)'}</option>
                <option value="local" disabled={!localAvailable}>Local — self-hosted{localAvailable ? '' : ' (no URL)'}</option>
                <option value="off">Off — text only</option>
              </select>
            </div>
          </section>

          {/* Realtime config */}
          <section className="voice-config-section">
            <span className="voice-config-section-label">Realtime conversation</span>
            <p className="voice-config-help">Marin and cedar are the newest GA voices (warmer timbre).</p>
            <div className="voice-config-grid">
              <label className="voice-config-field">
                <span>Model</span>
                <select
                  className="voice-config-select"
                  value={realtimeModel}
                  disabled={!realtimeAvailable}
                  onChange={e => update(setRealtimeModel, 'madarx:realtime-model')(e.target.value)}
                >
                  {REALTIME_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}
                </select>
              </label>
              <label className="voice-config-field">
                <span>Voice</span>
                <select
                  className="voice-config-select"
                  value={realtimeVoice}
                  disabled={!realtimeAvailable}
                  onChange={e => update(setRealtimeVoice, 'madarx:realtime-voice')(e.target.value)}
                >
                  {REALTIME_VOICES.map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </label>
            </div>
          </section>

          {/* Speaking style — prompt-level personality */}
          <section className="voice-config-section">
            <span className="voice-config-section-label">Speaking style</span>
            <p className="voice-config-help">
              Shapes how the agent talks — contractions, sentence length, fillers, warmth.
              Independent of the voice you pick above. Takes effect on the next session.
            </p>
            <div className="voice-config-grid voice-config-grid--one">
              <label className="voice-config-field">
                <span>Style</span>
                <select
                  className="voice-config-select"
                  value={speakingStyle}
                  onChange={e => update(setSpeakingStyle, 'madarx:speaking-style')(e.target.value)}
                >
                  {SPEAKING_STYLES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                </select>
              </label>
            </div>
            <p className="voice-config-help">
              {SPEAKING_STYLES.find(s => s.id === speakingStyle)?.hint || ''}
            </p>
          </section>

          {/* TTS-mode config */}
          <section className="voice-config-section">
            <span className="voice-config-section-label">Speak replies (TTS)</span>
            <p className="voice-config-help">Synthesizes the assistant&apos;s last reply when you tap the orb in TTS mode.</p>
            <div className="voice-config-grid">
              <label className="voice-config-field">
                <span>Provider</span>
                <select
                  className="voice-config-select"
                  value={ttsProvider}
                  onChange={e => update(setTtsProvider, 'madarx:tts-provider')(e.target.value)}
                >
                  <option value="openai" disabled={!capOpenaiTts}>OpenAI{capOpenaiTts ? '' : ' (no key)'}</option>
                  <option value="elevenlabs" disabled={!capElevenlabsTts}>ElevenLabs{capElevenlabsTts ? '' : ' (no key)'}</option>
                  <option value="local" disabled={!capLocalTts}>Local{capLocalTts ? '' : ' (no URL)'}</option>
                </select>
              </label>
              <label className="voice-config-field">
                <span>Voice id</span>
                <input
                  className="voice-config-input"
                  type="text"
                  placeholder={ttsProvider === 'elevenlabs' ? 'voice id' : 'alloy / ash / verse…'}
                  value={ttsVoice}
                  onChange={e => update(setTtsVoice, 'madarx:tts-voice')(e.target.value)}
                />
              </label>
            </div>
          </section>
    </div>
  );
}

function CapBadge({ label, on, pending }) {
  const cls = 'voice-cap-badge' + (on ? ' is-on' : '') + (pending ? ' is-pending' : '');
  return (
    <span className={cls}>
      <span className="voice-cap-dot" aria-hidden />
      {label}
    </span>
  );
}
