import { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '../../components/ui/Button';
import { AiLabel } from '../../components/ui/Badge';
import { EmptyState } from '../../components/ui/States';
import { IconAiBot } from '../../components/ui/icons';
import { ApiRequestError } from '../../api/client';
import { aiConsoleApi } from './aiConsoleApi';
import type { NlQueryResult, RulesChatResult } from './aiConsoleApi';
import './aiConsole.css';

/*
 * F092 자연어 조회(Text-to-SQL) + F025 규정 챗봇 콘솔 — SCR-13 경영분석 하위 패널.
 * 두 탭 동거: [자연어 조회] 질문→표 결과+생성 SQL 접기, [규정 챗봇] 질문→근거 룰 인용 답변.
 * 모든 AI 산출물은 AiLabel + provider/degraded 를 정직하게 표기(참고용 · 환각 방지).
 */
type Tab = 'nlquery' | 'rules';

export function AiConsolePanel() {
  const { t } = useTranslation();
  // 홈 AI 허브 딥링크(/analytics?tab=rules) 정합 — URL tab 파라미터로 초기 탭 결정.
  const [searchParams] = useSearchParams();
  const [tab, setTab] = useState<Tab>(searchParams.get('tab') === 'rules' ? 'rules' : 'nlquery');

  return (
    <section className="kx-card kx-aicon" aria-label={t('ai.console.title')}>
      <div className="kx-card__head">
        <div>
          <h2><IconAiBot className="kx-title-ic" size={18} />{t('ai.console.title')}</h2>
          <p className="kx-card__hint">{t('ai.console.subtitle')}</p>
        </div>
        <AiLabel>{t('ai.console.badge')}</AiLabel>
      </div>

      <div className="kx-seg" role="tablist" aria-label={t('ai.console.tabsAria')}>
        <button
          role="tab"
          aria-selected={tab === 'nlquery'}
          className={`kx-seg__btn ${tab === 'nlquery' ? 'is-active' : ''}`}
          onClick={() => setTab('nlquery')}
        >
          {t('ai.console.tabNlquery')}
        </button>
        <button
          role="tab"
          aria-selected={tab === 'rules'}
          className={`kx-seg__btn ${tab === 'rules' ? 'is-active' : ''}`}
          onClick={() => setTab('rules')}
        >
          {t('ai.console.tabRules')}
        </button>
      </div>

      {tab === 'nlquery' ? <NlQueryTab /> : <RulesChatTab />}
    </section>
  );
}

// ── 탭 1: 자연어 조회(Text-to-SQL) ──
function NlQueryTab() {
  const { t } = useTranslation();
  const [q, setQ] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<NlQueryResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [showSql, setShowSql] = useState(true);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!q.trim() || loading) return;
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const r = await aiConsoleApi.nlquery(q.trim());
      setResult(r);
    } catch (err) {
      setError(errorMessage(err, t));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="kx-aicon__pane">
      <form className="kx-aicon__ask" onSubmit={submit}>
        <input
          className="kx-input"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder={t('ai.nlquery.placeholder')}
          aria-label={t('ai.nlquery.inputAria')}
        />
        <Button variant="ai" type="submit" disabled={loading || !q.trim()}>
          {loading ? t('ai.common.running') : t('ai.nlquery.run')}
        </Button>
      </form>
      <p className="kx-aicon__note">{t('ai.nlquery.guardNote')}</p>

      {error && <div className="kx-aicon__error" role="alert">{error}</div>}

      {result && (
        <div className="kx-aicon__result">
          <div className="kx-aicon__meta">
            <span className="kx-aicon__prov">{providerLabel(result.provider, t)}</span>
            <span className="kx-aicon__count tnum">{t('ai.nlquery.rowCount', { n: result.rowCount })}</span>
            <button
              type="button"
              className="kx-aicon__toggle"
              onClick={() => setShowSql((s) => !s)}
              aria-expanded={showSql}
            >
              {showSql ? t('ai.nlquery.hideSql') : t('ai.nlquery.showSql')}
            </button>
          </div>

          {showSql && (
            <pre className="kx-aicon__sql" aria-label={t('ai.nlquery.sqlAria')}>
              <code>{result.sql}</code>
            </pre>
          )}

          {result.rowCount === 0 ? (
            <EmptyState title={t('ai.nlquery.emptyTitle')} description={t('ai.nlquery.emptyDesc')} />
          ) : (
            <div className="kx-table-scroll">
              <table className="kx-table kx-table--zebra">
                <thead>
                  <tr>
                    {result.columns.map((c) => (
                      <th key={c}>{c}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {result.rows.map((row, i) => (
                    <tr key={i}>
                      {result.columns.map((c) => (
                        <td key={c}>{cell(row[c])}</td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── 탭 2: 규정 챗봇 ──
function RulesChatTab() {
  const { t } = useTranslation();
  const [q, setQ] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<RulesChatResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!q.trim() || loading) return;
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const r = await aiConsoleApi.rulesChat(q.trim());
      setResult(r);
    } catch (err) {
      setError(errorMessage(err, t));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="kx-aicon__pane">
      <form className="kx-aicon__ask" onSubmit={submit}>
        <input
          className="kx-input"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder={t('ai.rules.placeholder')}
          aria-label={t('ai.rules.inputAria')}
        />
        <Button variant="ai" type="submit" disabled={loading || !q.trim()}>
          {loading ? t('ai.common.running') : t('ai.rules.run')}
        </Button>
      </form>
      <p className="kx-aicon__note">{t('ai.rules.groundNote')}</p>

      {error && <div className="kx-aicon__error" role="alert">{error}</div>}

      {result && (
        <div className="kx-aicon__result">
          <div className="kx-aicon__meta">
            <span className="kx-aicon__prov">{providerLabel(result.provider, t)}</span>
            {!result.grounded && (
              <span className="kx-aicon__ungrounded">{t('ai.rules.notFound')}</span>
            )}
            {result.degraded && result.grounded && (
              <span className="kx-aicon__degraded">{t('ai.rules.degraded')}</span>
            )}
          </div>

          <div className="kx-aicon__answer">{result.answer}</div>

          {result.citations.length > 0 && (
            <div className="kx-aicon__cites">
              <span className="kx-aicon__cites-h">{t('ai.rules.citations')}</span>
              <ul>
                {result.citations.map((c) => (
                  <li key={c.code}>
                    <code className="kx-aicon__code">{c.code}</code> {c.label}
                    {c.detail && <span className="kx-aicon__cite-detail"> · {c.detail}</span>}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── helpers ──
function cell(v: unknown): string {
  if (v === null || v === undefined) return '—';
  if (typeof v === 'object') return JSON.stringify(v);
  return String(v);
}

function providerLabel(provider: string, t: (k: string) => string): string {
  if (provider === 'claude') return t('ai.common.provClaude');
  if (provider === 'ollama') return t('ai.common.provOllama');
  if (provider === 'rules') return t('ai.common.provRules');
  return t('ai.common.provNone');
}

function errorMessage(err: unknown, t: (k: string) => string): string {
  if (err instanceof ApiRequestError) {
    // err.code 는 백엔드 오류코드 문자열(AI_UNAVAILABLE 은 공용 타입 유니온 밖 — string 비교).
    const code = err.code as string;
    if (code === 'AI_UNAVAILABLE') return t('ai.common.unavailable');
    if (code === 'VALIDATION') return err.message || t('ai.common.invalid');
    if (code === 'FORBIDDEN') return t('ai.common.forbidden');
    return err.message || t('ai.common.error');
  }
  return t('ai.common.error');
}
