import { useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../../store/authStore';
import { AiLabel } from '../../components/ui/Badge';
import { AiImage } from '../../components/ui/AiImage';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconBell, IconCheck, IconExhibitors, IconImage } from '../../components/ui/icons';
import { dashboardApi } from '../../api/endpoints';
import { ApiRequestError } from '../../api/client';
import type { DashboardData } from '../../api/types';
import { StatusPill, timeAgo } from '../work/workShared';
import {
  SAMPLE_EXHIBITORS,
  SAMPLE_FEED,
  SAMPLE_KPIS,
  SAMPLE_MILESTONES,
} from './sampleDashboard';
import './dashboard.css';

// Stitch organizer_dashboard 번들 이미지(실 KINTEX 촬영본 — 히어로 시각화 데코, AI 샘플 라벨).
const MOCK = `${import.meta.env.BASE_URL}mock/organizer_dashboard`;
const S7_AERIAL = `${MOCK}/img3.jpg`;

/*
 * SCR-02 주최자 대시보드. Stitch organizer_dashboard 이식.
 * 정상 경로: GET /api/events/{eventId}/dashboard (실집계 — milestones·kpis·exhibitors·feed).
 * 폴백: NETWORK/NOT_FOUND 시에만 sampleDashboard 로 강등(degraded 배너). 그 외 오류는 재시도 UI.
 * 백엔드가 빈배열을 주는 섹션은 빈 상태로 표기(가짜 수치로 덮지 않음).
 */
export function OrganizerDashboardPage() {
  const { t } = useTranslation();
  const { eventId } = useParams();
  const workspace = useAuthStore((s) => s.currentWorkspace());

  const eventName = workspace?.eventName ?? '2026 스마트팩토리 코리아';
  const hallLabel = workspace?.hallLabel ?? '제2전시장 홀7';
  const period =
    workspace && workspace.startDate
      ? `${workspace.startDate} ~ ${workspace.endDate}`
      : '2026.08.11 ~ 08.14';
  const dday = workspace?.dday ?? 31;

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

  const degraded = isDegradable(q.error);
  const data: DashboardData | null = q.data ?? (degraded ? FALLBACK : null);
  const hardError = q.isError && !degraded;

  return (
    <div className="kx-dash">
      {/* 행사 헤더 — 인증 워크스페이스 실데이터 */}
      <header className="kx-dash__event">
        <div>
          <h1 className="kx-dash__event-name">{eventName}</h1>
          <p className="kx-dash__event-meta">
            {t('common.brand')} {hallLabel} · {period}
          </p>
        </div>
        <span className="kx-dash__countdown tnum">{t('dashboard.countdown', { n: dday })}</span>
      </header>

      {degraded && (
        <div className="kx-dash__degraded-bar">
          <span className="kx-dash__degraded">{t('dashboard.degradedTag')}</span>
          {t('dashboard.degradedMsg')}
        </div>
      )}

      {q.isLoading && <DashboardSkeleton />}

      {hardError && (
        <ErrorState
          message={t('dashboard.loadError')}
          onRetry={() => q.refetch()}
        />
      )}

      {data && (
        <>
          {/* 히어로: 마일스톤 타임라인 */}
          <section className="kx-dash__hero" aria-label={t('dashboard.timelineAria')}>
            {data.milestones.length === 0 ? (
              <EmptyState title={t('dashboard.milestoneEmptyTitle')} description={t('dashboard.milestoneEmptyDesc')} />
            ) : (
              <ol className="kx-timeline">
                {data.milestones.map((m, i) => (
                  <li key={`${m.label}-${i}`} className={`kx-timeline__node is-${milestoneClass(m.state)}`}>
                    {i < data.milestones.length - 1 && (
                      <span className="kx-timeline__bar" aria-hidden="true" />
                    )}
                    <span className="kx-timeline__dot" aria-hidden="true">
                      {m.state === 'done' ? <IconCheck size={12} /> : null}
                    </span>
                    <div className="kx-timeline__label">
                      <span className="kx-timeline__d tnum">{ddayLabel(m.date)}</span>
                      <span className="kx-timeline__title">{m.label}</span>
                    </div>
                    <div className="kx-timeline__card">
                      <span className="kx-timeline__muted">{t(`dashboard.mstate.${normState(m.state)}`)}</span>
                    </div>
                  </li>
                ))}
              </ol>
            )}
          </section>

          {/* KPI 카드 */}
          <section className="kx-dash__kpis" aria-label={t('dashboard.kpisAria')}>
            {data.kpis.length === 0 ? (
              <EmptyState title={t('dashboard.kpiEmpty')} />
            ) : (
              data.kpis.map((k, i) => (
                <div key={`${k.label}-${i}`} className={`kx-kpi kx-kpi--${kpiTone(k.trend)}`}>
                  <span className="kx-kpi__label">{k.label}</span>
                  <strong className="kx-kpi__value tnum">{k.value}</strong>
                  {k.delta && (
                    <span className={`kx-delta kx-delta--${k.trend === 'down' ? 'down' : 'up'}`}>
                      {k.trend === 'down' ? '▼' : k.trend === 'up' ? '▲' : ''} {k.delta}
                    </span>
                  )}
                </div>
              ))
            )}
          </section>

          {/* 하단: 참가업체 테이블(2/3) + 알림·S7(1/3) */}
          <div className="kx-dash__split">
            <section className="kx-dash__table-wrap" aria-label={t('dashboard.exhibitorStatus')}>
              <div className="kx-dash__section-head">
                <h2><IconExhibitors className="kx-title-ic" size={18} />{t('dashboard.exhibitorStatus')}</h2>
                {degraded && <span className="kx-dash__degraded">{t('dashboard.sampleTag')}</span>}
              </div>
              {data.exhibitors.length === 0 ? (
                <EmptyState
                  title={t('dashboard.exhibitorEmptyTitle')}
                  description={t('dashboard.exhibitorEmptyDesc')}
                />
              ) : (
                <table className="kx-table">
                  <thead>
                    <tr>
                      <th>{t('dashboard.colBoothNo')}</th>
                      <th>{t('dashboard.colCompany')}</th>
                      <th>{t('dashboard.colStatus')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.exhibitors.map((r, i) => (
                      <tr key={`${r.boothNo}-${i}`}>
                        <td className="tnum">{r.boothNo}</td>
                        <td>{r.companyName}</td>
                        <td>
                          <StatusPill value={r.status} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </section>

            <aside className="kx-dash__aside">
              <section className="kx-feed" aria-label={t('dashboard.feedAria')}>
                <h2 className="kx-feed__title"><IconBell className="kx-title-ic" size={18} />{t('dashboard.feedTitle')}</h2>
                {data.feed.length === 0 ? (
                  <EmptyState title={t('dashboard.feedEmpty')} />
                ) : (
                  <ul className="kx-feed__list">
                    {data.feed.map((f) => (
                      <li key={f.id} className={`kx-feed__item is-${feedKind(f.kind)}`}>
                        <span className="kx-feed__dot" aria-hidden="true" />
                        <span className="kx-feed__text">{f.message}</span>
                        <span className="kx-feed__time">{timeAgo(f.at)}</span>
                      </li>
                    ))}
                  </ul>
                )}
              </section>

              <section className="kx-dash__s7" aria-label={t('dashboard.aerialAria')}>
                <div className="kx-dash__s7-head">
                  <h2><IconImage className="kx-title-ic" size={18} />{t('dashboard.aerialTitle')}</h2>
                  <AiLabel>S7</AiLabel>
                </div>
                <AiImage
                  imageUrl={S7_AERIAL}
                  status="DONE"
                  sample
                  watermarkText={t('common.aiWatermark')}
                  notice={t('common.aiNotice')}
                  shotLabel={t('dashboard.aerialShot')}
                  alt={t('dashboard.aerialAlt')}
                />
              </section>
            </aside>
          </div>
        </>
      )}
    </div>
  );
}

function DashboardSkeleton() {
  return (
    <div aria-hidden="true" style={{ display: 'grid', gap: 16 }}>
      <Skeleton height={72} radius={12} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[0, 1, 2, 3].map((i) => (
          <Skeleton key={i} height={92} radius={12} />
        ))}
      </div>
      <Skeleton height={260} radius={12} />
    </div>
  );
}

/** NETWORK/NOT_FOUND(백엔드 미배포·미접속) 만 샘플 폴백으로 강등. */
function isDegradable(error: unknown): boolean {
  return (
    error instanceof ApiRequestError &&
    (error.code === 'NETWORK' || error.code === 'NOT_FOUND' || error.code === 'NOT_IMPLEMENTED')
  );
}

function milestoneClass(state: string): string {
  if (state === 'done') return 'done';
  if (state === 'current') return 'imminent';
  return 'upcoming';
}
function normState(state: string): 'done' | 'current' | 'upcoming' {
  if (state === 'done') return 'done';
  if (state === 'current') return 'current';
  return 'upcoming';
}
function kpiTone(trend: string): 'normal' | 'warn' | 'error' {
  return trend === 'down' ? 'warn' : 'normal';
}
function feedKind(kind: string): string {
  if (kind === 'approval' || kind === 'approved') return 'approved';
  if (kind === 'violation' || kind === 'rejected') return 'rejected';
  if (kind === 'deadline') return 'deadline';
  return 'submitted';
}
/** "YYYY-MM-DD" → D-데이 라벨(오늘 기준). */
function ddayLabel(dateStr: string): string {
  const d = new Date(dateStr);
  if (Number.isNaN(d.getTime())) return dateStr;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  d.setHours(0, 0, 0, 0);
  const diff = Math.round((d.getTime() - today.getTime()) / 86400000);
  if (diff === 0) return 'D-DAY';
  return diff > 0 ? `D-${diff}` : `D+${-diff}`;
}

/**
 * 샘플 폴백(백엔드 shape 매핑) — 정상 경로는 실 API. NETWORK/NOT_FOUND 시에만 사용.
 * 근거: 기존 sampleDashboard.ts(경계면 시연 데이터)를 DashboardData 형태로 강등 변환.
 */
const FALLBACK: DashboardData = {
  milestones: SAMPLE_MILESTONES.map((m) => ({
    label: m.title,
    date: '',
    state: m.state === 'imminent' ? 'current' : m.state === 'current' ? 'current' : m.state,
  })),
  kpis: SAMPLE_KPIS.map((k) => ({
    label: k.label,
    value: k.value,
    delta: k.sub ?? null,
    trend: k.tone === 'error' ? 'down' : k.tone === 'warn' ? 'down' : 'flat',
  })),
  exhibitors: SAMPLE_EXHIBITORS.map((e) => ({
    companyName: e.company,
    boothNo: e.boothNo,
    status: e.designStatus,
  })),
  feed: SAMPLE_FEED.map((f) => ({ id: f.key, kind: f.kind, message: f.text, at: '' })),
};
