/*
 * SCR-37 다국어 콘텐츠 관리 [M17 / F069]. 참조: design.md §3 SCR-37.
 * 상단: 언어 커버리지(한/영/중/일) · 좌: 번역 매트릭스(콘텐츠 × 대상언어 상태) · 우: 병렬 편집(원문 KO ↔ 번역) + 검수완료.
 * ★실 API 전환: GET /api/cms/contents + GET/PUT /api/cms/contents/{id}/translations. 언어별 upsert·검수완료 실동작.
 * AI 자동 번역/재생성: POST /api/cms/contents/{id}/translations/ai?lang= (AiTextRouter Claude→Ollama 폴백) 실배선 —
 * 성공 시 trans_status='ai' 초벌 채움, degraded(AI 미가용) 시 저장 없이 안내만(환각 방지).
 */
import { useEffect, useMemo, useState } from 'react';
import { Button } from '../../components/ui/Button';
import { ApiRequestError } from '../../api/client';
import { cmsApi, type CmsContent, type CmsTranslation, type Lang, type TransStatus } from './cmsApi';
import { IconSpark, IconWarning, IconClose } from '../../components/ui/icons';
import './cms.css';

type Target = 'en' | 'zh' | 'ja';
const TARGETS: { key: Target; label: string }[] = [
  { key: 'en', label: 'English (EN)' },
  { key: 'zh', label: 'Chinese (ZH)' },
  { key: 'ja', label: 'Japanese (JA)' },
];
const COV_LANGS: { key: Lang; label: string }[] = [
  { key: 'ko', label: '한국어 (KO)' },
  { key: 'en', label: 'English (EN)' },
  { key: 'zh', label: 'Chinese (ZH)' },
  { key: 'ja', label: 'Japanese (JA)' },
];

const STATUS_META: Record<TransStatus, { label: string; cls: string }> = {
  none: { label: '미번역', cls: 'kx-cms-pill--none' },
  ai: { label: 'AI 초벌', cls: 'kx-cms-pill--ai' },
  reviewed: { label: '검수완료', cls: 'kx-cms-pill--published' },
};

const GLOSSARY = [
  { ko: '홀', en: 'Hall' },
  { ko: '안내', en: 'Guide' },
  { ko: '부스', en: 'Booth' },
];

const AI_TRANSLATE_HINT = 'AI(Claude)로 원문(KO)을 대상 언어로 번역합니다. 초벌은 사람 검수를 거쳐 확정하세요.';

type TransMap = Record<string, Partial<Record<Lang, CmsTranslation>>>;

function fmtRel(iso: string | null): string {
  if (!iso) return '-';
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString('ko-KR', { dateStyle: 'medium' });
}

export function MultilingualCmsPage() {
  const [target, setTarget] = useState<Target>('en');
  const [contents, setContents] = useState<CmsContent[]>([]);
  const [transMap, setTransMap] = useState<TransMap>({});
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [draftText, setDraftText] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await cmsApi.listContents({ size: 100 });
        const list = res.items;
        const pairs = await Promise.all(
          list.map(async (c) => {
            try {
              const trs = await cmsApi.getTranslations(c.id);
              const byLang: Partial<Record<Lang, CmsTranslation>> = {};
              trs.forEach((t) => (byLang[t.lang] = t));
              return [c.id, byLang] as const;
            } catch {
              return [c.id, {}] as const;
            }
          }),
        );
        if (cancelled) return;
        const map: TransMap = {};
        pairs.forEach(([id, byLang]) => (map[id] = byLang));
        setContents(list);
        setTransMap(map);
        setSelectedId(list[0]?.id ?? null);
      } catch (e) {
        if (!cancelled) setError(e instanceof ApiRequestError ? e.message : '번역 데이터를 불러오지 못했습니다.');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const selected = useMemo(
    () => contents.find((c) => c.id === selectedId) ?? null,
    [contents, selectedId],
  );

  const coverage = useMemo(() => {
    const total = contents.length || 1;
    return COV_LANGS.map((l) => {
      const covered = contents.filter((c) => {
        const t = transMap[c.id]?.[l.key];
        return t && t.transStatus !== 'none' && !!(t.title || t.body);
      }).length;
      return { label: l.label, pct: Math.round((covered / total) * 100) };
    });
  }, [contents, transMap]);

  // 선택/대상 변경 시 편집 텍스트 동기화(안내 문구도 초기화)
  useEffect(() => {
    setNotice(null);
    if (!selected) {
      setDraftText('');
      return;
    }
    setDraftText(transMap[selected.id]?.[target]?.title ?? '');
  }, [selected, target, transMap]);

  // 현재 대상 언어의 번역 상태(AI 초벌 여부 표기용)
  const targetStatus: TransStatus = selected
    ? transMap[selected.id]?.[target]?.transStatus ?? 'none'
    : 'none';

  /**
   * AI 자동 번역/재생성(F100 배선) — 원문(KO)→target 초벌(trans_status='ai').
   * 성공: 초안 채움 + "AI 초벌 — 검수 필요" 안내. AI 일시 불가(degraded): 부드러운 안내만(저장 안 됨).
   */
  async function aiTranslate() {
    if (!selected || busy) return;
    setBusy(true);
    setError(null);
    setNotice(null);
    try {
      const res = await cmsApi.aiTranslate(selected.id, target);
      if (res.degraded || !res.translation) {
        setNotice(res.message ?? 'AI 번역을 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.');
        return;
      }
      const tr = res.translation;
      setTransMap((prev) => ({
        ...prev,
        [selected.id]: { ...(prev[selected.id] ?? {}), [tr.lang]: tr },
      }));
      setDraftText(tr.title ?? '');
      setNotice('AI 초벌 번역이 채워졌습니다 — 반드시 사람 검수 후 적용하세요.');
    } catch (e) {
      setError(e instanceof ApiRequestError ? e.message : 'AI 자동 번역에 실패했습니다.');
    } finally {
      setBusy(false);
    }
  }

  async function save(status: TransStatus) {
    if (!selected) return;
    setBusy(true);
    setError(null);
    setNotice(null);
    try {
      const rows = await cmsApi.saveTranslation(selected.id, {
        lang: target,
        title: draftText,
        body: transMap[selected.id]?.[target]?.body ?? '',
        transStatus: status,
      });
      const byLang: Partial<Record<Lang, CmsTranslation>> = {};
      rows.forEach((t) => (byLang[t.lang] = t));
      setTransMap((prev) => ({ ...prev, [selected.id]: byLang }));
    } catch (e) {
      setError(e instanceof ApiRequestError ? e.message : '번역 저장에 실패했습니다.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="kx-page">
      <header className="kx-cms__head">
        <div>
          <h1 className="kx-cms__title">다국어 콘텐츠 관리</h1>
          <p className="kx-cms__subtitle">번역 매트릭스 · 언어별 저장 → 사람 검수 워크플로 · 용어집·톤 가이드</p>
        </div>
      </header>

      {error && (
        <div className="kx-cms-alert" role="alert">
          <IconWarning size={14} /> {error}
        </div>
      )}
      {notice && (
        <div className="kx-cms-alert kx-cms-alert--info" role="status">
          <IconSpark size={14} /> {notice}
        </div>
      )}

      {/* 커버리지 요약 */}
      <div className="kx-i18n-cov" aria-label="언어 커버리지">
        {coverage.map((c) => (
          <div className="kx-i18n-covcard" key={c.label}>
            <div className="kx-i18n-covcard__top">
              <span>{c.label}</span>
              <span className="kx-i18n-covcard__pct">{c.pct}%</span>
            </div>
            <div className="kx-i18n-bar">
              <span className="kx-i18n-bar__fill" style={{ width: `${c.pct}%` }} />
            </div>
          </div>
        ))}
      </div>

      <div className="kx-i18n-main">
        {/* 좌: 번역 매트릭스 */}
        <section className="kx-card" aria-label="번역 매트릭스">
          <div className="kx-i18n-toolbar">
            <div className="kx-seg" role="tablist" aria-label="대상 언어">
              {TARGETS.map((t) => (
                <button
                  key={t.key}
                  role="tab"
                  aria-selected={target === t.key}
                  className={`kx-seg__btn ${target === t.key ? 'is-active' : ''}`}
                  onClick={() => setTarget(t.key)}
                >
                  {t.label}
                </button>
              ))}
            </div>
            <Button
              variant="ai"
              leadingIcon={<IconSpark size={16} />}
              onClick={aiTranslate}
              disabled={!selected || busy}
              title={AI_TRANSLATE_HINT}
            >
              {busy ? 'AI 번역 중…' : 'AI 자동 번역'}
            </Button>
          </div>

          <div className="kx-table-scroll">
            {loading ? (
              <div className="kx-cms-empty">불러오는 중…</div>
            ) : contents.length === 0 ? (
              <div className="kx-cms-empty">콘텐츠가 없습니다.</div>
            ) : (
              <table className="kx-table kx-i18n-table">
                <thead>
                  <tr>
                    <th style={{ width: '30%' }}>콘텐츠 / 원문(KO)</th>
                    <th>번역본 ({target.toUpperCase()})</th>
                    <th className="kx-i18n-cell--c" style={{ width: 96 }}>상태</th>
                    <th className="kx-i18n-cell--r" style={{ width: 96 }}>최근 업데이트</th>
                  </tr>
                </thead>
                <tbody>
                  {contents.map((c) => {
                    const t = transMap[c.id]?.[target];
                    const st = t?.transStatus ?? 'none';
                    const m = STATUS_META[st];
                    return (
                      <tr
                        key={c.id}
                        className={c.id === selectedId ? 'is-active' : ''}
                        onClick={() => setSelectedId(c.id)}
                      >
                        <td>
                          <div className="kx-i18n-row__key">{c.title}</div>
                          <div className="kx-i18n-row__id">{c.id}</div>
                        </td>
                        <td className={t?.title ? '' : 'kx-i18n-row__trans--empty'}>
                          {t?.title || '번역 대기 중…'}
                        </td>
                        <td className="kx-i18n-cell--c">
                          <span className={`kx-cms-pill ${m.cls}`}>{m.label}</span>
                        </td>
                        <td className="kx-i18n-cell--r">{fmtRel(t?.updatedAt ?? null)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </section>

        {/* 우: 병렬 편집기 */}
        <aside className="kx-card kx-i18n-editor" aria-label="번역 편집">
          <div className="kx-i18n-editor__head">
            <span className="kx-cms-sublabel">번역 편집: 원문(KO) ↔ 번역({target.toUpperCase()})</span>
            <button className="kx-icon-btn" title="닫기" aria-label="편집 닫기" onClick={() => setSelectedId(null)}>
              <IconClose size={16} />
            </button>
          </div>

          {!selected ? (
            <div className="kx-cms-empty">좌측에서 콘텐츠를 선택하세요.</div>
          ) : (
            <>
              <div className="kx-cms-field">
                <span className="kx-cms-label">Content ID</span>
                <div className="kx-i18n-row__id" style={{ color: 'var(--color-primary-700)', fontWeight: 700 }}>
                  {selected.id}
                </div>
              </div>

              <div className="kx-cms-field">
                <span className="kx-cms-label">원문 (KO)</span>
                <div className="kx-i18n-src">{transMap[selected.id]?.ko?.title || selected.title}</div>
              </div>

              <div className="kx-cms-field">
                <span className="kx-cms-label">
                  번역 ({target.toUpperCase()})
                  {targetStatus === 'ai' && (
                    <span className="kx-cms-pill kx-cms-pill--ai" style={{ marginLeft: 8 }}>
                      AI 초벌 — 검수 필요
                    </span>
                  )}
                </span>
                <textarea
                  className="kx-cms-textarea kx-i18n-editor__ta"
                  value={draftText}
                  onChange={(e) => setDraftText(e.target.value)}
                  placeholder="번역을 입력하세요"
                />
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button
                    variant="ghost"
                    leadingIcon={<IconSpark size={14} />}
                    onClick={aiTranslate}
                    disabled={busy}
                    title={AI_TRANSLATE_HINT}
                  >
                    AI 재생성
                  </Button>
                </div>
              </div>

              <div className="kx-cms-field">
                <span className="kx-cms-sublabel">Glossary</span>
                <div className="kx-i18n-glossary">
                  {GLOSSARY.map((g) => (
                    <div className="kx-i18n-glossary__row" key={g.ko}>
                      <b>{g.ko}</b>
                      <span>→ {g.en}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="kx-i18n-editor__actions">
                <Button variant="secondary" onClick={() => save('ai')} disabled={busy}>
                  임시 저장
                </Button>
                <Button onClick={() => save('reviewed')} disabled={busy}>
                  적용 · 검수완료
                </Button>
              </div>
            </>
          )}
        </aside>
      </div>
    </div>
  );
}
