/*
 * W12 시스템관리 — 오류 로그 조회 (읽기전용).
 * 정본: GET /api/admin/error-log?errorCode&page&size → PageResponse<ErrorLogRow> (ErrorLogController).
 * 보안: summary 는 백엔드에서 요약 1줄로만 저장/전달(스택트레이스·민감정보 제외, §0-3).
 */
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { Button } from '../../components/ui/Button';
import { IconSearch } from '../../components/ui/icons';
import { fmtDateTime } from '../work/workShared';
import { errorLogApi } from './systemBasicsApi';
import { Pager } from './LoginHistoryPage';
import './admin-modules.css';

export function ErrorLogPage() {
  const { t } = useTranslation();
  const [errorCode, setErrorCode] = useState('');
  const [applied, setApplied] = useState('');
  const [page, setPage] = useState(0);
  const size = 20;

  const q = useQuery({
    queryKey: ['admin-error-log', applied, page],
    queryFn: () => errorLogApi.list(applied, page, size),
    retry: false,
  });
  const rows = q.data?.items ?? [];
  const total = q.data?.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / size));

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('errorLog.title')}</h1>
          <p className="kx-adm__subtitle">{t('errorLog.subtitle')}</p>
        </div>
      </header>

      <section className="kx-card kx-adm-filter" aria-label={t('errorLog.filterAria')}>
        <div className="kx-adm-filter__grid">
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('errorLog.code')}</span>
            <input className="kx-adm-field__input" value={errorCode} onChange={(e) => setErrorCode(e.target.value)}
                   placeholder={t('errorLog.codePh')} />
          </label>
          <div className="kx-adm-filter__actions">
            <Button leadingIcon={<IconSearch size={16} />} onClick={() => { setPage(0); setApplied(errorCode); }}>
              {t('sysadmin.search')}
            </Button>
          </div>
        </div>
      </section>

      {q.isLoading && <Skeleton height={320} radius={12} />}
      {q.isError && !q.isLoading && <ErrorState message={t('errorLog.loadError')} onRetry={() => q.refetch()} />}

      {!q.isLoading && !q.isError && (
        <section className="kx-card kx-adm-table-card">
          {rows.length === 0 ? (
            <EmptyState title={t('errorLog.emptyTitle')} description={t('errorLog.emptyDesc')} />
          ) : (
            <>
              <div className="kx-table-scroll">
                <table className="kx-table kx-table--zebra">
                  <thead>
                    <tr>
                      <th>{t('errorLog.colTime')}</th>
                      <th>{t('errorLog.colCode')}</th>
                      <th>{t('errorLog.colMethod')}</th>
                      <th>{t('errorLog.colPath')}</th>
                      <th>{t('errorLog.colSummary')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((r) => (
                      <tr key={r.id}>
                        <td className="kx-adm-mono">{fmtDateTime(r.createdAt)}</td>
                        <td><span className="kx-adm-pill kx-adm-pill--error">{r.errorCode ?? '-'}</span></td>
                        <td className="kx-adm-mono">{r.method ?? '-'}</td>
                        <td className="kx-adm-mono">{r.path ?? '-'}</td>
                        <td className="kx-adm-summary">{r.summary ?? '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pager page={page} totalPages={totalPages} total={total} onPrev={() => setPage((p) => Math.max(0, p - 1))}
                     onNext={() => setPage((p) => Math.min(totalPages - 1, p + 1))} />
            </>
          )}
        </section>
      )}
    </div>
  );
}
