/*
 * SCR-A9 테넌트(전시관) 관리·온보딩 (M18 · §1A · 플랫폼 슈퍼관리자 전용). Stitch scr_a9 이식.
 * ★ 실배선(G-01 해소): GET /api/admin/tenants(목록) · POST /api/admin/tenants(등록).
 *   백엔드 TenantAdminController 실존 — 종전 하드코딩 배열·disabled 버튼(STALE "미구현")을 제거하고
 *   react-query 목록 + 등록 모달로 배선. 상태·수치는 서버 권위. 코드 규칙은 서버 재검증(클라 사전검증만).
 * 우측 온보딩 위저드는 선택 테넌트 상태 기반 IA 표시(2단계 브랜딩·시드·격리 스모크는 후속).
 */
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { Button } from '../../components/ui/Button';
import { ErrorState, Skeleton } from '../../components/ui/States';
import { KxDataTable, type KxColumn } from '../../components/KxDataTable';
import { IconCheck, IconPlus } from '../../components/ui/icons';
import { errMessage, useToast } from '../work/workShared';
import { tenantApi, TENANT_STATUSES, type Tenant, type TenantCreateBody } from './adminCrudApi';
import './admin-modules.css';

const WIZARD_STEPS = ['create', 'domain', 'brand', 'master', 'admin', 'smoke', 'activate'];

/** 코드 규칙(백엔드 CODE 패턴과 동일) — 사전 검증용. 최종 검증은 서버 권위. */
const CODE_RE = /^[a-z0-9-]{2,40}$/;

export function TenantAdminPage() {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [selected, setSelected] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const listQ = useQuery({ queryKey: ['admin-tenants'], queryFn: tenantApi.list, retry: false });
  const tenants = listQ.data ?? [];

  const createM = useMutation({
    mutationFn: (body: TenantCreateBody) => tenantApi.create(body),
    onSuccess: (created) => {
      show(t('tenant.created'));
      setModalOpen(false);
      setSelected(created.code);
      qc.invalidateQueries({ queryKey: ['admin-tenants'] });
    },
    onError: (e) => show(errMessage(e)),
  });

  // 선택 테넌트(미선택 시 첫 행). 위저드 진행 단계는 상태 기반.
  const tenant = tenants.find((tn) => tn.code === selected) ?? tenants[0] ?? null;
  const currentStep = !tenant ? 0 : tenant.status === 'onboarding' ? 3 : WIZARD_STEPS.length;

  const columns = useMemo<KxColumn<Tenant>[]>(
    () => [
      { key: 'name', header: t('tenant.venue'), value: (tn) => tn.name,
        render: (tn) => <span className="kx-adm-tenants__name">{tn.name}</span> },
      { key: 'code', header: t('tenant.code'), value: (tn) => tn.code,
        render: (tn) => <span className="kx-adm-mono">{tn.code}</span> },
      { key: 'domain', header: t('tenant.domain'), value: (tn) => tn.domain ?? '',
        render: (tn) => <span className="kx-adm-muted">{tn.domain ?? '—'}</span> },
      { key: 'status', header: t('tenant.status'), value: (tn) => t(`tenant.tstatus.${tn.status}`, { defaultValue: tn.status }),
        render: (tn) => <TenantStatus status={tn.status} /> },
      { key: 'events', header: t('tenant.events'), numeric: true, value: (tn) => tn.events },
      { key: 'users', header: t('tenant.users'), numeric: true, value: (tn) => tn.users },
    ],
    [t],
  );

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('tenant.title')}</h1>
          <p className="kx-adm__subtitle">{t('tenant.subtitle')}</p>
        </div>
        <Button leadingIcon={<IconPlus size={16} />} onClick={() => setModalOpen(true)}>
          {t('tenant.addVenue')}
        </Button>
      </header>

      <div className="kx-adm-tenant">
        <section className="kx-card kx-adm-tenant__list" aria-label={t('tenant.listAria')}>
          <div className="kx-adm-tenant__lhead">
            <h2>{t('tenant.venue')}</h2>
          </div>

          {listQ.isLoading ? (
            <div style={{ padding: 16 }}><Skeleton height={200} radius={8} /></div>
          ) : listQ.isError ? (
            <div style={{ padding: 16 }}>
              <ErrorState message={t('tenant.loadError')} onRetry={() => listQ.refetch()} />
            </div>
          ) : (
            <div className="kx-adm-tenant__tbl">
              <KxDataTable
                columns={columns}
                rows={tenants}
                rowKey={(tn) => tn.code}
                onRowClick={(tn) => setSelected(tn.code)}
                isRowSelected={(tn) => tn.code === tenant?.code}
                csvFileName="tenants"
                ariaLabel={t('tenant.listAria')}
                emptyTitle={t('tenant.emptyTitle')}
                emptyDescription={t('tenant.emptyDesc')}
              />
            </div>
          )}
        </section>

        <aside className="kx-card kx-adm-tenant__wizard" aria-label={t('tenant.wizardAria')}>
          {tenant ? (
            <>
              <h2 className="kx-adm-wiz__title">{t('tenant.onboardingOf', { name: tenant.name })}</h2>
              <p className="kx-adm-muted">{t('tenant.dataOnboarding')}</p>
              <ol className="kx-adm-wiz">
                {WIZARD_STEPS.map((key, i) => {
                  const state = i < currentStep ? 'done' : i === currentStep ? 'current' : 'todo';
                  return (
                    <li key={key} className={`kx-adm-wiz__step is-${state}`}>
                      <span className="kx-adm-wiz__dot" aria-hidden="true">
                        {state === 'done' ? <IconCheck size={14} /> : i + 1}
                      </span>
                      <span className="kx-adm-wiz__body">
                        <span className="kx-adm-wiz__label">{t(`tenant.wiz.${key}.label`)}</span>
                        <span className="kx-adm-wiz__desc">{t(`tenant.wiz.${key}.desc`)}</span>
                      </span>
                    </li>
                  );
                })}
              </ol>
            </>
          ) : (
            <p className="kx-adm-muted">{t('tenant.emptyDesc')}</p>
          )}
        </aside>
      </div>

      {modalOpen && (
        <TenantModal
          t={t}
          existingCodes={tenants.map((tn) => tn.code)}
          saving={createM.isPending}
          onClose={() => setModalOpen(false)}
          onSubmit={(body) => createM.mutate(body)}
        />
      )}
      {toast}
    </div>
  );
}

function TenantStatus({ status }: { status: string }) {
  const { t } = useTranslation();
  const cls = status === 'active' ? 'success' : status === 'onboarding' ? 'warn' : 'error';
  return <span className={`kx-adm-pill kx-adm-pill--${cls}`}>{t(`tenant.tstatus.${status}`, { defaultValue: status })}</span>;
}

function TenantModal({
  t,
  existingCodes,
  saving,
  onClose,
  onSubmit,
}: {
  t: TFunction;
  existingCodes: string[];
  saving: boolean;
  onClose: () => void;
  onSubmit: (body: TenantCreateBody) => void;
}) {
  const [code, setCode] = useState('');
  const [name, setName] = useState('');
  const [domain, setDomain] = useState('');
  const [status, setStatus] = useState<string>('onboarding');
  const [error, setError] = useState<string | null>(null);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    const c = code.trim().toLowerCase();
    if (!c) {
      setError(t('tenant.errCodeRequired'));
      return;
    }
    if (!CODE_RE.test(c)) {
      setError(t('tenant.errCodePattern'));
      return;
    }
    if (existingCodes.includes(c)) {
      setError(t('tenant.errDupCode'));
      return;
    }
    if (!name.trim()) {
      setError(t('tenant.errNameRequired'));
      return;
    }
    onSubmit({ code: c, name: name.trim(), domain: domain.trim() || null, status });
  }

  return (
    <div className="kx-adm-modal" role="dialog" aria-modal="true" aria-labelledby="tenant-modal-title">
      <div className="kx-adm-modal__backdrop" onClick={onClose} />
      <form className="kx-adm-modal__panel" onSubmit={submit}>
        <h2 id="tenant-modal-title" className="kx-adm-modal__title">{t('tenant.modalTitle')}</h2>
        <div className="kx-adm-modal__grid">
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('tenant.code')}</span>
            <input
              className="kx-adm-field__input kx-adm-mono"
              value={code}
              placeholder={t('tenant.codePlaceholder')}
              onChange={(e) => setCode(e.target.value)}
              autoFocus
            />
            <span className="kx-adm-field__hint">{t('tenant.codeHint')}</span>
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('tenant.nameLabel')}</span>
            <input
              className="kx-adm-field__input"
              value={name}
              placeholder={t('tenant.namePlaceholder')}
              onChange={(e) => setName(e.target.value)}
            />
          </label>
          <label className="kx-adm-field kx-adm-field--full">
            <span className="kx-adm-field__label">{t('tenant.domain')}</span>
            <input
              className="kx-adm-field__input kx-adm-mono"
              value={domain}
              placeholder={t('tenant.domainPlaceholder')}
              onChange={(e) => setDomain(e.target.value)}
            />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('tenant.status')}</span>
            <select className="kx-adm-field__select" value={status} onChange={(e) => setStatus(e.target.value)}>
              {TENANT_STATUSES.map((s) => (
                <option key={s} value={s}>{t(`tenant.tstatus.${s}`)}</option>
              ))}
            </select>
          </label>
        </div>
        {error && <p className="kx-adm-modal__error" role="alert">{error}</p>}
        <div className="kx-adm-modal__actions">
          <Button variant="ghost" type="button" onClick={onClose}>{t('tenant.cancel')}</Button>
          <Button type="submit" disabled={saving}>{saving ? t('tenant.saving') : t('tenant.save')}</Button>
        </div>
      </form>
    </div>
  );
}
