import React, { useEffect, useState } from 'react';
import { Save, CheckCircle, AlertTriangle } from '../../../icons';
import api from '../../../utils/api';
import { useToast } from '../../Toasts/useToast';
import '../../DeckyFleet.css';
import '../../PersonaGeneration.css';
import './LLMTab.css';

interface LLMPayload {
  provider: string;
  base_url: string | null;
  model: string;
  timeout: number;
  api_key_set: boolean;
}

interface PutBody {
  provider?: string;
  base_url?: string | null;
  model?: string;
  timeout?: number;
  api_key?: string;
}

const DEFAULTS: LLMPayload = {
  provider: 'ollama',
  base_url: null,
  model: 'llama3.1',
  timeout: 60,
  api_key_set: false,
};

interface Props {
  isAdmin: boolean;
}

export const LLMTab: React.FC<Props> = ({ isAdmin }) => {
  const { push } = useToast();
  const [cfg, setCfg] = useState<LLMPayload>(DEFAULTS);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [apiKeyInput, setApiKeyInput] = useState('');
  const [clearApiKey, setClearApiKey] = useState(false);

  useEffect(() => {
    api.get<LLMPayload>('/realism/llm')
      .then((r) => setCfg(r.data))
      .catch(() => setError('Failed to load LLM config.'))
      .finally(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    const body: PutBody = {
      provider: cfg.provider,
      base_url: cfg.base_url || null,
      model: cfg.model,
      timeout: cfg.timeout,
    };
    if (clearApiKey) body.api_key = '';
    else if (apiKeyInput.trim()) body.api_key = apiKeyInput.trim();

    try {
      const r = await api.put<LLMPayload>('/realism/llm', body);
      setCfg(r.data);
      setApiKeyInput('');
      setClearApiKey(false);
      push({ text: 'LLM CONFIG SAVED', tone: 'matrix', icon: 'terminal' });
    } catch (err: any) {
      const detail = err?.response?.data?.detail;
      const status = err?.response?.status;
      if (status === 403) setError('Admin role required to save.');
      else if (status === 400 && detail) setError(`Validation failed: ${detail}`);
      else setError('Save failed.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <div className="llm-tab-root"><div className="dim" style={{ padding: '16px 0' }}>Loading…</div></div>;
  }

  return (
    <div className="llm-tab-root">
      <div className="info-banner">
        <div>
          <strong>Scope:</strong> configures the LLM backend used for{' '}
          <em>email bodies, drafts, and notes</em> generated by the realism
          subsystem. Changes are persisted and hot-reloaded immediately; the
          orchestrator worker picks them up within one refresh tick (~5 min).
        </div>
        {error && (
          <div className="info-line alert-text" style={{ marginTop: 8 }}>
            <AlertTriangle size={12} /> {error}
          </div>
        )}
      </div>

      <div className="form-grid">
        <div className="tweak-group">
          <label>Provider</label>
          <select
            className="input"
            value={cfg.provider}
            disabled={!isAdmin}
            onChange={(e) => setCfg({ ...cfg, provider: e.target.value })}
          >
            <option value="ollama">Ollama</option>
          </select>
        </div>

        <div className="tweak-group">
          <label>Model</label>
          <input
            className="input"
            type="text"
            placeholder="llama3.1"
            value={cfg.model}
            disabled={!isAdmin}
            onChange={(e) => setCfg({ ...cfg, model: e.target.value })}
          />
        </div>
      </div>

      <div className="form-grid single-col">
        <div className="tweak-group">
          <label>Base URL</label>
          <input
            className="input"
            type="url"
            placeholder="http://127.0.0.1:11434 — leave blank for local subprocess"
            value={cfg.base_url || ''}
            disabled={!isAdmin}
            onChange={(e) => setCfg({ ...cfg, base_url: e.target.value || null })}
          />
          <span className="field-hint">
            Blank = use local <span className="mono">ollama run</span> subprocess.
            Set to the daemon URL to target a remote host.
          </span>
        </div>
      </div>

      <div className="form-grid">
        <div className="tweak-group">
          <label>Timeout (seconds)</label>
          <input
            className="input"
            type="number"
            min={1}
            step={1}
            value={cfg.timeout}
            disabled={!isAdmin}
            onChange={(e) => {
              const v = parseFloat(e.target.value);
              if (v > 0) setCfg({ ...cfg, timeout: v });
            }}
          />
        </div>

        <div className="tweak-group">
          <label>API Key (write-only)</label>
          {cfg.api_key_set && !clearApiKey ? (
            <>
              <div className="key-badge">
                <CheckCircle size={11} /> KEY SET — enter a new value to rotate
              </div>
              {isAdmin && (
                <div className="actions">
                  <button
                    className="btn ghost"
                    style={{ padding: '3px 10px', fontSize: '0.65rem' }}
                    onClick={() => { setClearApiKey(true); setApiKeyInput(''); }}
                  >
                    CLEAR
                  </button>
                </div>
              )}
            </>
          ) : (
            <>
              <input
                className="input"
                type="password"
                placeholder={clearApiKey
                  ? '(will be cleared on save)'
                  : 'Enter key to set — blank keeps existing'}
                value={apiKeyInput}
                disabled={!isAdmin || clearApiKey}
                onChange={(e) => setApiKeyInput(e.target.value)}
              />
              {clearApiKey && isAdmin && (
                <div className="actions">
                  <button
                    className="btn ghost"
                    style={{ padding: '3px 10px', fontSize: '0.65rem' }}
                    onClick={() => setClearApiKey(false)}
                  >
                    CANCEL CLEAR
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {isAdmin && (
        <div className="actions">
          <button
            className="btn violet"
            onClick={handleSave}
            disabled={saving}
          >
            <Save size={12} /> {saving ? 'SAVING…' : 'SAVE'}
          </button>
        </div>
      )}
    </div>
  );
};
