/*
 * W12 시스템관리 — 로그인 이력(접속 세션) 조회 (읽기전용).
 * 정본: GET /api/admin/login-history?result&userId&page&size → PageResponse<LoginHistoryRow> (LoginHistoryController).
 * 보안: 이메일/IP 는 백엔드에서 마스킹되어 도착(원문 미저장·미노출, §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 { loginHistoryApi } from './systemBasicsApi';
import './admin-modules.css';

const RESULTS = ['', 'SUCCESS', 'FAIL', 'LOCKED'];

export function LoginHistoryPage() {
  const { t } = useTranslation();
  const [result, setResult] = useState('');
  const [userId, setUserId] = useState('');
  const [applied, setApplied] = useState<{ result: string; userId: string }>({ result: '', userId: '' });
  const [page, setPage] = useState(0);
  const size = 20;

  const q = useQuery({
    queryKey: ['admin-login-history', applied, page],
    queryFn: () => loginHistoryApi.list(applied.result, applied.userId, 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('loginHistory.title')}</h1>
          <p className="kx-adm__subtitle">{t('loginHistory.subtitle')}</p>
        </div>
      </header>

      <section className="kx-card kx-adm-filter" aria-label={t('loginHistory.filterAria')}>
        <div className="kx-adm-filter__grid">
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('loginHistory.result')}</span>
            <select className="kx-adm-field__select" value={result} onChange={(e) => setResult(e.target.value)}>
              {RESULTS.map((r) => (
                <option key={r || 'all'} value={r}>
                  {r ? t(`loginHistory.result_${r}`) : t('loginHistory.allResults')}
                </option>
              ))}
            </select>
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('loginHistory.userId')}</span>
            <input className="kx-adm-field__input" value={userId} onChange={(e) => setUserId(e.target.value)}
                   placeholder={t('loginHistory.userIdPh')} />
          </label>
          <div className="kx-adm-filter__actions">
            <Button leadingIcon={<IconSearch size={16} />}
                    onClick={() => { setPage(0); setApplied({ result, userId }); }}>
              {t('sysadmin.search')}
            </Button>
          </div>
        </div>
      </section>

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

      {!q.isLoading && !q.isError && (
        <section className="kx-card kx-adm-table-card">
          {rows.length === 0 ? (
            <EmptyState title={t('loginHistory.emptyTitle')} description={t('loginHistory.emptyDesc')} />
          ) : (
            <>
              <div className="kx-table-scroll">
                <table className="kx-table kx-table--zebra">
                  <thead>
                    <tr>
                      <th>{t('loginHistory.colTime')}</th>
                      <th>{t('loginHistory.colResult')}</th>
                      <th>{t('loginHistory.colUser')}</th>
                      <th>{t('loginHistory.colEmail')}</th>
                      <th>{t('loginHistory.colIp')}</th>
                      <th>{t('loginHistory.colReason')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((r) => (
                      <tr key={r.id}>
                        <td className="kx-adm-mono">{fmtDateTime(r.createdAt)}</td>
                        <td><ResultPill value={r.result} /></td>
                        <td className="kx-adm-mono">{r.userId ?? '-'}</td>
                        <td>{r.emailMasked ?? '-'}</td>
                        <td className="kx-adm-mono">{r.ipMasked ?? '-'}</td>
                        <td className="kx-adm-muted">{r.failReason ?? '-'}</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>
  );
}

function ResultPill({ value }: { value: string | null }) {
  const { t } = useTranslation();
  const v = (value ?? '').toUpperCase();
  const tone = v === 'SUCCESS' ? 'success' : v === 'FAIL' || v === 'LOCKED' ? 'error' : 'neutral';
  const label = v ? t(`loginHistory.result_${v}`) : '-';
  return <span className={`kx-adm-pill kx-adm-pill--${tone}`}>{label}</span>;
}

export function Pager({ page, totalPages, total, onPrev, onNext }: {
  page: number; totalPages: number; total: number; onPrev: () => void; onNext: () => void;
}) {
  const { t } = useTranslation();
  return (
    <div className="kx-adm-pager">
      <p className="kx-adm-pager__info tnum">{t('sysadmin.totalN', { n: total.toLocaleString() })}</p>
      <div className="kx-adm-pager__nav">
        <Button variant="ghost" onClick={onPrev} disabled={page === 0}>{t('sysadmin.prev')}</Button>
        <span className="kx-adm-pager__page tnum">{page + 1} / {totalPages}</span>
        <Button variant="ghost" onClick={onNext} disabled={page >= totalPages - 1}>{t('sysadmin.next')}</Button>
      </div>
    </div>
  );
}
