import type { ComponentType } from 'react';
import { AiImage } from '../../components/ui/AiImage';
import { AiLabel, DdayChip, RoleBadge, StatusBadge, type FlowStatus } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import * as Icons from '../../components/ui/icons';
import type { IconProps } from '../../components/ui/icons';
import './styleguide.css';

/*
 * SCR-17 §9 "시스템 아이콘 라이브러리" — components/ui/icons.tsx 의 선 SVG 세트를 자동 열거한다.
 * 네임스페이스 import 로 아이콘 추가/제거 시 자동 동기화(신규 아이콘 제작 아님 — 기존 세트 나열).
 */
const ICON_ENTRIES = (Object.entries(Icons) as [string, unknown][])
  .filter(([name, val]) => name.startsWith('Icon') && typeof val === 'function')
  .sort((a, b) => a[0].localeCompare(b[0]))
  .map(([name, comp]) => [name.replace(/^Icon/, ''), comp as ComponentType<IconProps>] as const);

/*
 * SCR-17 컴포넌트 가이드 (§1 실증 스타일가이드 / 스토리북 성격).
 * 내부 전용(/_styleguide) — 제품 내비 비노출. 색·치수 권위는 design.md §1(tokens.css).
 * 실 데이터·API 없음(정적 참조). 기존 공통 컴포넌트를 실물 렌더한다.
 */
const STATUS_FLOW: FlowStatus[] = [
  'draft', 'submitted', 'ai-review', 'approved', 'rejected', 'building', 'inspected',
];

const SWATCHES = [
  { name: 'KINTEX Blue', varName: '--color-primary-600', hex: '#0066B3' },
  { name: 'Primary 700', varName: '--color-primary-700', hex: '#004C86' },
  { name: 'AI Accent', varName: '--color-ai-accent', hex: '#6D4AFF' },
  { name: 'Success', varName: '--color-success', hex: '#0E8A5F' },
  { name: 'Error', varName: '--color-error', hex: '#D92D20' },
  { name: 'Warning', varName: '--color-warning', hex: '#B45309' },
  { name: 'Neutral 900', varName: '--color-neutral-900', hex: '#101828' },
  { name: 'Neutral 200', varName: '--color-neutral-200', hex: '#E4E7EC' },
];

const MOCK = `${import.meta.env.BASE_URL}mock/organizer_dashboard/img1.jpg`;

export function ComponentGuidePage() {
  return (
    <div className="kx-sg">
      <header className="kx-sg__head">
        <div>
          <p className="kx-sg__eyebrow">System Reference</p>
          <h1 className="kx-sg__title">컴포넌트 가이드</h1>
          <p className="kx-sg__desc">
            KINTEX AI 디자인 시스템 — 고신뢰·정밀 정보 처리 B2B 전시 환경. 색·치수 권위는 design.md §1.
          </p>
        </div>
        <span className="kx-sg__ver">design.md v1.3 · 내부 전용</span>
      </header>

      <div className="kx-sg__grid">
        {/* 1. 타이포 & 컬러 */}
        <section className="kx-sg-card" data-accent="primary">
          <h2 className="kx-sg-card__title">타이포그래피 & 컬러</h2>
          <div className="kx-sg__type">
            <p className="kx-sg__t-display">전시공간 최적화 엔진</p>
            <p className="kx-sg__t-headline">도면 분석 보고서</p>
            <p className="kx-sg__t-title">부스 배치 시뮬레이션</p>
            <p className="kx-sg__t-body">
              본문 텍스트 — 참가업체 설계 스펙과 규정 검증 결과를 정밀하게 표시합니다. Pretendard 14px.
            </p>
          </div>
          <div className="kx-sg__swatches">
            {SWATCHES.map((s) => (
              <div key={s.name} className="kx-sg__swatch">
                <span className="kx-sg__swatch-chip" style={{ background: `var(${s.varName})` }} />
                <span className="kx-sg__swatch-name">{s.name}</span>
                <span className="kx-sg__swatch-hex tnum">{s.hex}</span>
              </div>
            ))}
          </div>
        </section>

        {/* 2. AI 전용 요소 */}
        <section className="kx-sg-card" data-accent="ai">
          <h2 className="kx-sg-card__title">AI 전용 요소</h2>
          <div className="kx-sg__ai-row">
            <AiLabel />
            <AiLabel>AI 수요예측</AiLabel>
            <AiLabel>AI 검토</AiLabel>
          </div>
          <div className="kx-sg__aiimg">
            <AiImage
              imageUrl={MOCK}
              status="DONE"
              sample
              watermarkText="AI 생성 예상 이미지 — 실제 시공 결과와 다를 수 있습니다"
              notice="AI 생성 이미지는 계약·심사 서류에 사용할 수 없습니다 — 시공 기준은 도면입니다"
              shotLabel="S1 정면"
              versionTag="설계 v2"
              alt="AI 초안 컴포넌트 예시"
            />
          </div>
          <div className="kx-sg__violations">
            <span className="kx-sg__viol">📍 피난 통로 차단</span>
            <span className="kx-sg__viol">📍 바닥하중 초과</span>
          </div>
        </section>

        {/* 3. 버튼 & 액션 */}
        <section className="kx-sg-card" data-accent="primary">
          <h2 className="kx-sg-card__title">버튼 & 액션</h2>
          <div className="kx-sg__btn-row">
            <Button variant="primary">Primary</Button>
            <Button variant="secondary">Secondary</Button>
            <Button variant="ghost">Ghost</Button>
            <Button variant="ai" leadingIcon="✦">AI 제안 레이아웃</Button>
            <Button variant="danger">삭제</Button>
            <Button variant="primary" disabled>Disabled</Button>
          </div>
          <div className="kx-sg__btn-row">
            <button className="kx-sg__icon-btn" aria-label="편집">✎</button>
            <button className="kx-sg__icon-btn" aria-label="삭제">🗑</button>
            <button className="kx-sg__icon-btn" aria-label="공유">↗</button>
          </div>
        </section>

        {/* 4. 상태 배지 & 칩 */}
        <section className="kx-sg-card" data-accent="success">
          <h2 className="kx-sg-card__title">상태 배지 & 칩</h2>
          <div className="kx-sg__chip-row">
            {STATUS_FLOW.map((s) => (
              <StatusBadge key={s} status={s} />
            ))}
          </div>
          <div className="kx-sg__chip-row">
            <DdayChip dday={30} />
            <DdayChip dday={3} />
            <DdayChip dday={-1} />
            <RoleBadge role="ORGANIZER" />
            <RoleBadge role="HALL_MANAGER" />
            <span className="kx-badge kx-badge--role">Hall 1A</span>
            <span className="kx-badge kx-badge--dday-warn">High Traffic</span>
          </div>
        </section>

        {/* 5. 데이터 시각화 (범례·게이지 — 실제는 Recharts로 대체) */}
        <section className="kx-sg-card" data-accent="primary">
          <h2 className="kx-sg-card__title">데이터 시각화</h2>
          <p className="kx-sg-card__note">차트 구현은 Recharts 사용 (SCR-13·14·16). 여기서는 토큰·범례만 실증.</p>
          <div className="kx-sg__gauge">
            <div className="kx-barlist__top">
              <span>전시장 점유율</span>
              <span className="tnum">78% / 임계치 85%</span>
            </div>
            <div className="kx-barlist__track">
              <span className="kx-barlist__fill is-warning" style={{ width: '78%' }} />
            </div>
          </div>
          <ul className="kx-sg__legend">
            <li><span className="kx-dot is-busy" /> 매우 혼잡</li>
            <li><span className="kx-dot is-moderate" /> 다소 혼잡</li>
            <li><span className="kx-dot is-smooth" /> 원활</li>
          </ul>
        </section>

        {/* 6. 폼 요소 */}
        <section className="kx-sg-card" data-accent="primary">
          <h2 className="kx-sg-card__title">폼 요소</h2>
          <div className="kx-sg__form">
            <label className="kx-sg__field">
              <span>기본 Input</span>
              <input className="kx-sg__input" placeholder="부스번호 입력" />
            </label>
            <label className="kx-sg__field">
              <span>에러 Input</span>
              <input className="kx-sg__input is-error" defaultValue="A-999" aria-invalid />
              <em className="kx-sg__err-msg">존재하지 않는 부스입니다.</em>
            </label>
            <label className="kx-sg__field">
              <span>Dropdown</span>
              <select className="kx-select">
                <option>기본 부스</option>
                <option>프리미엄</option>
              </select>
            </label>
            <div className="kx-sg__check-row">
              <label className="kx-sg__check"><input type="checkbox" defaultChecked /> 방염 확인</label>
              <label className="kx-sg__check"><input type="radio" name="sg-r" defaultChecked /> 주간</label>
              <label className="kx-sg__check"><input type="radio" name="sg-r" /> 야간</label>
            </div>
          </div>
        </section>

        {/* 7. 피드백 & 오버레이 */}
        <section className="kx-sg-card" data-accent="ai">
          <h2 className="kx-sg-card__title">피드백 & 오버레이</h2>
          <div className="kx-sg__toast">데이터가 저장되었습니다</div>
          <div className="kx-sg__alert" role="alert">⚠ 소방법 위반 구역 3곳</div>
          <div className="kx-sg__states">
            <div className="kx-sg__state-box">
              <Skeleton height={12} width="80%" />
              <Skeleton height={12} width="60%" />
            </div>
            <div className="kx-sg__state-box">
              <EmptyState title="데이터 없음" description="빈 상태 예시" />
            </div>
            <div className="kx-sg__state-box">
              <ErrorState message="불러오기 실패" onRetry={() => {}} />
            </div>
          </div>
        </section>

        {/* 8. 시스템 아이콘 라이브러리 (R17-01 · SCR-17 스펙 9항목) */}
        <section className="kx-sg-card kx-sg-card--wide" data-accent="primary">
          <h2 className="kx-sg-card__title">시스템 아이콘 라이브러리</h2>
          <p className="kx-sg-card__note">
            components/ui/icons.tsx 선 SVG 세트 · fill:none / stroke:currentColor 상속 · size 조절. 총 {ICON_ENTRIES.length}종.
          </p>
          <ul className="kx-sg__icons">
            {ICON_ENTRIES.map(([name, Comp]) => (
              <li key={name} className="kx-sg__icon-cell">
                <Comp size={22} aria-hidden="true" />
                <span className="kx-sg__icon-name">{name}</span>
              </li>
            ))}
          </ul>
        </section>
      </div>
    </div>
  );
}
