import { useEffect, useState } from 'react';
import {
  useSentimentSettings,
  useUpdateSentimentSettings,
  useTestSentimentProvider,
} from '../../hooks/useAdmin';
import { Dropdown, type DropdownOption } from '../ui/Dropdown';
import { SkeletonTable } from '../ui/Skeleton';
import type { SentimentTestResult } from '../../lib/types';

const SOURCE_LABEL: Record<string, string> = {
  database: 'configured here',
  environment: 'from environment (.env)',
  none: 'not configured',
};

const PROVIDER_LABELS: Record<string, string> = {
  openai: 'OpenAI — web search',
  gemini: 'Google Gemini — web search',
  deepseek: 'DeepSeek — cheap, no web search',
  xai: 'xAI Grok — web search',
  openai_compatible: 'OpenAI-compatible — custom URL',
};

function providerLabel(p: string): string {
  return PROVIDER_LABELS[p] ?? p;
}

export function SentimentProviderSettings() {
  const { data, isLoading, isError, error } = useSentimentSettings();
  const update = useUpdateSentimentSettings();
  const test = useTestSentimentProvider();

  const [provider, setProvider] = useState('openai');
  const [model, setModel] = useState('');
  const [apiKey, setApiKey] = useState('');
  const [baseUrl, setBaseUrl] = useState('');
  const [testResult, setTestResult] = useState<SentimentTestResult | null>(null);

  useEffect(() => {
    if (data) {
      setProvider(data.provider);
      setModel(data.model);
      setBaseUrl(data.base_url ?? '');
    }
  }, [data]);

  if (isLoading) return <SkeletonTable rows={3} cols={2} />;
  if (isError) return <p className="text-sm text-red-400">{(error as Error)?.message || 'Failed to load sentiment settings'}</p>;
  if (!data) return null;

  const grounded = data.web_search_providers ?? ['openai', 'gemini'];
  const needsBaseUrl = (data.custom_base_url_providers ?? ['openai_compatible']).includes(provider);
  const isGrounded = grounded.includes(provider);

  const providerOptions: DropdownOption[] = data.valid_providers.map((p) => ({
    value: p,
    label: providerLabel(p),
  }));

  const onProviderChange = (next: string) => {
    setProvider(next);
    const defaults = data.default_models;
    if (!model || Object.values(defaults).includes(model)) {
      setModel(defaults[next] ?? '');
    }
  };

  const onSave = () => {
    setTestResult(null);
    update.mutate({
      provider,
      model,
      ...(needsBaseUrl ? { base_url: baseUrl } : {}),
      ...(apiKey ? { api_key: apiKey } : {}),
    });
    setApiKey('');
  };

  const onTest = () => {
    test.mutate('AAPL', { onSuccess: (res) => setTestResult(res) });
  };

  const keyConfigured = data.api_key_configured;

  return (
    <div className="glass p-5 space-y-4">
      <div>
        <h3 className="text-sm font-semibold text-gray-200">Sentiment LLM Provider</h3>
        <p className="mt-1 text-xs text-gray-500">
          Switch the model that powers sentiment analysis without redeploying. Applies to the
          scheduled sentiment job and manual fetches on the next run.
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <label className="block space-y-1">
          <span className="text-xs text-gray-400">Provider</span>
          <Dropdown value={provider} onChange={onProviderChange} options={providerOptions} ariaLabel="Sentiment provider" />
        </label>

        <label className="block space-y-1">
          <span className="text-xs text-gray-400">Model</span>
          <input
            type="text"
            value={model}
            onChange={(e) => setModel(e.target.value)}
            placeholder={data.default_models[provider] || 'model id'}
            className="w-full input-glass px-3 py-2 text-sm"
          />
        </label>
      </div>

      {needsBaseUrl && (
        <label className="block space-y-1">
          <span className="text-xs text-gray-400">Base URL</span>
          <input
            type="text"
            value={baseUrl}
            onChange={(e) => setBaseUrl(e.target.value)}
            placeholder="https://openrouter.ai/api/v1"
            className="w-full input-glass px-3 py-2 text-sm"
          />
          <span className="text-[11px] text-gray-600">OpenAI-compatible Chat Completions endpoint (OpenRouter, Together, Groq, local Ollama…).</span>
        </label>
      )}

      {!isGrounded && (
        <div className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-4 py-2.5 text-xs text-amber-300">
          ⚠ No live web search. This provider scores sentiment from the model's training knowledge,
          not current news — cheaper, but not real-time. OpenAI and Gemini are grounded in live search.
        </div>
      )}

      <label className="block space-y-1">
        <span className="text-xs text-gray-400">API Key</span>
        <input
          type="password"
          value={apiKey}
          onChange={(e) => setApiKey(e.target.value)}
          autoComplete="new-password"
          placeholder={keyConfigured ? '•••••••••• (leave blank to keep current)' : 'Paste API key…'}
          className="w-full input-glass px-3 py-2 text-sm"
        />
        <span className="text-[11px] text-gray-500">
          Key status:{' '}
          <span className={keyConfigured ? 'text-emerald-400' : 'text-amber-400'}>
            {SOURCE_LABEL[data.api_key_source] ?? data.api_key_source}
          </span>
          {' '}· write-only, never displayed
        </span>
      </label>

      <div className="flex flex-wrap items-center gap-2">
        <button className="btn-primary px-4 py-2 text-sm" onClick={onSave} disabled={update.isPending}>
          {update.isPending ? 'Saving…' : 'Save Provider'}
        </button>
        <button
          className="px-4 py-2 text-sm rounded border border-white/[0.1] text-gray-300 hover:text-white disabled:opacity-50"
          onClick={onTest}
          disabled={test.isPending}
        >
          {test.isPending ? 'Testing (AAPL)…' : 'Test Connection'}
        </button>
        <span className="text-[11px] text-gray-500">Test fetches live sentiment for AAPL with the saved config.</span>
      </div>

      {testResult && (
        <div
          className={`rounded-lg border px-4 py-3 text-sm ${
            testResult.ok
              ? 'border-emerald-500/20 bg-emerald-500/10 text-emerald-300'
              : 'border-red-500/20 bg-red-500/10 text-red-400'
          }`}
        >
          {testResult.ok ? (
            <>
              <span className="font-medium">✓ {testResult.provider} / {testResult.model}</span> — {testResult.ticker}:{' '}
              <span className="font-semibold">{testResult.classification}</span>{' '}
              <span className="num">({testResult.confidence}%)</span>
              {testResult.reasoning && <p className="mt-1 text-xs text-emerald-300/80">{testResult.reasoning}</p>}
            </>
          ) : (
            <>
              <span className="font-medium">✗ Test failed</span>
              <p className="mt-1 text-xs">{testResult.error}</p>
            </>
          )}
        </div>
      )}
    </div>
  );
}
