/*
 * SCR /exhibitors — 주최자용 참가업체 관리(#41).
 * 진입: 사이드바 "참가업체 관리"(전용 라우트 — 종전 대시보드 폴백 해소).
 * 정본: GET /api/events/{eventId}/exhibitors (ExhibitorList — 요약 + 로스터).
 * 구성: ①상단 요약 밴드 ②검색/상태 필터 ③참가사 로스터(회사·부스·설계/정산·연락) ④상세 드로어.
 * ★ 상태·금액은 서버 계산 권위 — 프론트는 표시/클라이언트 필터만. 이모지 금지·선 SVG 아이콘.
 */
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { Offcanvas } from '../../components/ui/Offcanvas';
import { KxDataTable, type KxColumn } from '../../components/KxDataTable';
import { IconUsers, IconExhibitors, IconCheckCircle, IconSettlement } from '../../components/ui/icons';
import { useResolvedEventId } from '../../hooks/useResolvedEventId';
import { exhibitorsApi } from './exhibitorsApi';
import type {
  DesignStatus,
  ExhibitorRow,
  InvoiceStatus,
  SaleStatus,
} from './exhibitorsApi';
import './exhibitors.css';

type SaleFilter = '' | SaleStatus;

const SALE_FILTERS: SaleFilter[] = ['', 'sold', 'held', 'available'];

/** 상태 → 톤(색 클래스). 미상은 muted. */
function saleTone(s: SaleStatus | null): string {
  return s === 'sold' ? 'ok' : s === 'held' ? 'info' : 'muted';
}
function designTone(s: DesignStatus | null): string {
  return s === 'approved' ? 'ok' : s === 'rejected' ? 'error' : s === 'review' ? 'info' : 'muted';
}
function invoiceTone(s: InvoiceStatus | null): string {
  if (s === 'paid') return 'ok';
  if (s === 'overdue') return 'error';
  if (s === 'invoiced') return 'info';
  return 'muted';
}

function saleLabel(t: TFunction, s: SaleStatus | null): string {
  return t(`exhibitorsPage.sale.${s ?? 'none'}`, { defaultValue: '-' });
}
function designLabel(t: TFunction, s: DesignStatus | null): string {
  return t(`exhibitorsPage.design.${s ?? 'none'}`, { defaultValue: '-' });
}
function invoiceLabel(t: TFunction, s: InvoiceStatus | null): string {
  return t(`exhibitorsPage.invoice.${s ?? 'none'}`, { defaultValue: '-' });
}

function fmtWon(n: number): string {
  return `${n.toLocaleString('ko-KR')}`;
}
function fmtArea(a: number | null): string {
  return a == null ? '-' : `${a.toLocaleString('ko-KR')}`;
}

export function ExhibitorsPage() {
  const { t } = useTranslation();
  const eventId = useResolvedEventId();
  const [saleFilter, setSaleFilter] = useState<SaleFilter>('');
  const [selected, setSelected] = useState<ExhibitorRow | null>(null);

  const q = useQuery({
    queryKey: ['exhibitors', eventId],
    queryFn: () => exhibitorsApi.list(eventId as string),
    enabled: !!eventId,
    retry: false,
  });

  // 세그먼트(판매상태) 필터만 여기서 — 검색·정렬·페이지·CSV 는 KxDataTable 담당.
  const rows = useMemo(() => {
    const all = q.data?.exhibitors ?? [];
    return saleFilter ? all.filter((r) => r.saleStatus === saleFilter) : all;
  }, [q.data, saleFilter]);

  const columns = useMemo<KxColumn<ExhibitorRow>[]>(
    () => [
      { key: 'company', header: t('exhibitorsPage.colCompany'), value: (r) => r.companyName,
        render: (r) => <span className="kx-exh__company">{r.companyName}</span> },
      { key: 'booth', header: t('exhibitorsPage.colBooth'), value: (r) => r.boothNo ?? '',
        render: (r) => <span className="tnum">{r.boothNo ?? '-'}</span> },
      { key: 'type', header: t('exhibitorsPage.colType'),
        value: (r) => (r.boothType ? t(`exhibitorsPage.boothType.${r.boothType}`, { defaultValue: r.boothType }) : ''),
        render: (r) => (r.boothType ? t(`exhibitorsPage.boothType.${r.boothType}`, { defaultValue: r.boothType }) : '-') },
      { key: 'area', header: t('exhibitorsPage.colArea'), numeric: true, value: (r) => r.areaM2 ?? null,
        render: (r) => fmtArea(r.areaM2) },
      { key: 'sale', header: t('exhibitorsPage.colSale'), value: (r) => saleLabel(t, r.saleStatus),
        render: (r) => <Pill tone={saleTone(r.saleStatus)} label={saleLabel(t, r.saleStatus)} /> },
      { key: 'design', header: t('exhibitorsPage.colDesign'), value: (r) => designLabel(t, r.designStatus),
        render: (r) => <Pill tone={designTone(r.designStatus)} label={designLabel(t, r.designStatus)} /> },
      { key: 'settlement', header: t('exhibitorsPage.colSettlement'), value: (r) => invoiceLabel(t, r.invoiceStatus),
        render: (r) => (
          <>
            <Pill tone={invoiceTone(r.invoiceStatus)} label={invoiceLabel(t, r.invoiceStatus)} />
            {r.outstanding > 0 && (
              <span className="kx-exh__due tnum">{t('exhibitorsPage.dueShort', { won: fmtWon(r.outstanding) })}</span>
            )}
          </>
        ) },
      { key: 'contact', header: t('exhibitorsPage.colContact'),
        value: (r) => r.contactName ?? r.contactPhone ?? '',
        render: (r) => r.contactName ?? r.contactPhone ?? <span className="kx-exh__muted">{t('exhibitorsPage.contactNone')}</span> },
    ],
    [t],
  );

  if (!eventId) {
    return (
      <div className="kx-page">
        <PageHeader t={t} />
        <EmptyState title={t('exhibitorsPage.noEventTitle')} description={t('exhibitorsPage.noEventDesc')} />
      </div>
    );
  }

  const summary = q.data?.summary;

  return (
    <div className="kx-page">
      <PageHeader t={t} eventName={q.data?.eventName} />

      {/* 요약 밴드 */}
      {q.isLoading ? (
        <div className="kx-exh__kpis" aria-hidden="true">
          {[0, 1, 2, 3].map((i) => (
            <Skeleton key={i} height={92} radius={12} />
          ))}
        </div>
      ) : summary ? (
        <section className="kx-exh__kpis" aria-label={t('exhibitorsPage.kpisAria')}>
          <KpiCard icon={<IconUsers size={16} />} label={t('exhibitorsPage.kpiTotal')} value={String(summary.total)} tone="info" />
          <KpiCard icon={<IconCheckCircle size={16} />} label={t('exhibitorsPage.kpiContracted')} value={String(summary.contracted)} tone="ok" />
          <KpiCard icon={<IconExhibitors size={16} />} label={t('exhibitorsPage.kpiDesignApproved')} value={String(summary.designApproved)} tone="ok" />
          <KpiCard
            icon={<IconSettlement size={16} />}
            label={t('exhibitorsPage.kpiOutstanding')}
            value={String(summary.outstandingCount)}
            tone={summary.outstandingCount > 0 ? 'error' : 'muted'}
          />
        </section>
      ) : null}

      {/* 목록 카드 */}
      <section className="kx-card kx-exh__list-card" aria-label={t('exhibitorsPage.listTitle')}>
        {q.isLoading ? (
          <div style={{ display: 'grid', gap: 8 }} aria-hidden="true">
            {[0, 1, 2, 3, 4].map((i) => (
              <Skeleton key={i} height={44} radius={8} />
            ))}
          </div>
        ) : q.isError ? (
          <ErrorState message={t('exhibitorsPage.loadError')} onRetry={() => q.refetch()} />
        ) : (
          <KxDataTable
            columns={columns}
            rows={rows}
            rowKey={(r) => r.boothId}
            onRowClick={setSelected}
            isRowSelected={(r) => r.boothId === selected?.boothId}
            searchPlaceholder={t('exhibitorsPage.searchPlaceholder')}
            csvFileName={`exhibitors_${eventId}`}
            ariaLabel={t('exhibitorsPage.listTitle')}
            emptyTitle={t('exhibitorsPage.emptyTitle')}
            emptyDescription={t('exhibitorsPage.emptyDesc')}
            toolbarStart={
              <div className="kx-seg" role="tablist" aria-label={t('exhibitorsPage.saleFilterLabel')}>
                {SALE_FILTERS.map((v) => (
                  <button
                    key={v || 'all'}
                    role="tab"
                    aria-selected={saleFilter === v}
                    className={`kx-seg__btn ${saleFilter === v ? 'is-active' : ''}`}
                    onClick={() => setSaleFilter(v)}
                  >
                    {v === '' ? t('exhibitorsPage.filterAll') : saleLabel(t, v)}
                  </button>
                ))}
              </div>
            }
          />
        )}
      </section>

      {/* 상세 드로어(부스·서류·연락) */}
      <Offcanvas
        open={!!selected}
        onClose={() => setSelected(null)}
        title={selected?.companyName ?? t('exhibitorsPage.detailTitle')}
        width={420}
      >
        {selected && <ExhibitorDetail t={t} row={selected} />}
      </Offcanvas>
    </div>
  );
}

function ExhibitorDetail({ t, row }: { t: TFunction; row: ExhibitorRow }) {
  return (
    <div className="kx-exh__detail">
      <dl className="kx-exh__dl">
        <DetailRow k={t('exhibitorsPage.boothLabel')} v={row.boothNo ?? '-'} />
        <DetailRow k={t('exhibitorsPage.typeLabel')} v={row.boothType ? t(`exhibitorsPage.boothType.${row.boothType}`, { defaultValue: row.boothType }) : '-'} />
        <DetailRow k={t('exhibitorsPage.areaLabel')} v={row.areaM2 == null ? '-' : `${fmtArea(row.areaM2)} m²`} />
      </dl>

      <h3 className="kx-exh__detail-h">{t('exhibitorsPage.statusSection')}</h3>
      <dl className="kx-exh__dl">
        <DetailRow k={t('exhibitorsPage.saleLabel')} v={<Pill tone={saleTone(row.saleStatus)} label={saleLabel(t, row.saleStatus)} />} />
        <DetailRow k={t('exhibitorsPage.designLabel')} v={<Pill tone={designTone(row.designStatus)} label={designLabel(t, row.designStatus)} />} />
        <DetailRow k={t('exhibitorsPage.settlementLabel')} v={<Pill tone={invoiceTone(row.invoiceStatus)} label={invoiceLabel(t, row.invoiceStatus)} />} />
        <DetailRow
          k={t('exhibitorsPage.outstandingLabel')}
          v={<span className="tnum">{t('exhibitorsPage.won', { won: fmtWon(row.outstanding) })}</span>}
        />
      </dl>

      <h3 className="kx-exh__detail-h">{t('exhibitorsPage.contactSection')}</h3>
      <dl className="kx-exh__dl">
        <DetailRow k={t('exhibitorsPage.contactNameLabel')} v={row.contactName ?? '-'} />
        <DetailRow k={t('exhibitorsPage.contactPhoneLabel')} v={row.contactPhone ?? '-'} />
      </dl>
    </div>
  );
}

function DetailRow({ k, v }: { k: string; v: React.ReactNode }) {
  return (
    <div className="kx-exh__dl-row">
      <dt>{k}</dt>
      <dd>{v}</dd>
    </div>
  );
}

function Pill({ tone, label }: { tone: string; label: string }) {
  return <span className={`kx-exh__pill kx-exh__pill--${tone}`}>{label}</span>;
}

function KpiCard({
  icon,
  label,
  value,
  tone,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  tone: 'info' | 'ok' | 'error' | 'muted';
}) {
  return (
    <div className={`kx-kpi kx-exh__kpi kx-exh__kpi--${tone}`}>
      <span className="kx-kpi__label">
        {icon}
        {label}
      </span>
      <strong className="kx-kpi__value tnum">{value}</strong>
    </div>
  );
}

function PageHeader({ t, eventName }: { t: TFunction; eventName?: string }) {
  return (
    <header className="kx-exh__head">
      <div>
        <h1 className="kx-page__title">{t('exhibitorsPage.title')}</h1>
        <p className="kx-page__subtitle">{eventName ? `${eventName} · ${t('exhibitorsPage.subtitle')}` : t('exhibitorsPage.subtitle')}</p>
      </div>
    </header>
  );
}
