import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '../../components/ui/Button';
import { DdayChip } from '../../components/ui/Badge';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconArrowRight, IconCheck, IconCheckCircle, IconPlus, IconStar } from '../../components/ui/icons';
import { ApiRequestError } from '../../api/client';
import { useResolvedEventId } from '../../hooks/useResolvedEventId';
import {
  FULFILLMENT,
  SPONSOR_KPIS,
  SPONSOR_STATUS_LABEL,
  SPONSOR_TIERS,
  SPONSORS,
  type SponsorContractStatus,
} from './sampleMarketing';
import { marketingApi, type SponsorDto, type SponsorshipViewDto, type TierDto } from './marketingApi';
import './marketing.css';

/*
 * SCR-34 스폰서십 패키지·판매 관리 (M12 / F070). Stitch scr_34_sponsorship 이식.
 * 정상 경로: GET /api/events/{eventId}/sponsorship (KPI·티어·스폰서·이행물).
 * 폴백: 오프라인 강등 시 sampleMarketing 시연 데이터.
 */
export function SponsorshipPage() {
  const eventId = useResolvedEventId();
  const [selectedSponsor, setSelectedSponsor] = useState<string>('');

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

  const degraded = isDegradable(q.error);
  const view: SponsorshipViewDto | null = q.data ?? (degraded ? SAMPLE_VIEW : null);
  const hardError = q.isError && !degraded;

  const sponsors = view?.sponsors ?? [];
  const active = sponsors.find((s) => s.id === selectedSponsor) ?? sponsors[0] ?? null;

  return (
    <div className="kx-mkt">
      <header className="kx-mkt__head">
        <div>
          <h1 className="kx-mkt__title">스폰서십 · 판매 관리</h1>
          <p className="kx-mkt__subtitle">패키지 티어 · 스폰서 계약 · 이행물 추적</p>
        </div>
        <div className="kx-mkt__head-actions">
          {degraded && (
            <span className="kx-vis__degraded" title="스폰서십 API 미연결 — 시연 데이터">오프라인 — 샘플</span>
          )}
          <Button leadingIcon={<IconPlus size={16} />}>신규 세일즈 리드</Button>
        </div>
      </header>

      {!eventId && (
        <EmptyState title="행사를 선택해 주세요" description="스폰서십 현황을 조회할 행사가 지정되지 않았습니다." />
      )}

      {eventId && q.isLoading && !degraded && (
        <div style={{ display: 'grid', gap: 16 }}>
          <Skeleton height={92} radius={12} />
          <Skeleton height={420} radius={12} />
        </div>
      )}

      {hardError && <ErrorState message="스폰서십 현황을 불러오지 못했습니다." onRetry={() => q.refetch()} />}

      {view && (
        <>
          <section className="kx-mkt__kpis" aria-label="스폰서십 핵심 지표">
            {view.kpis.map((k) => (
              <div key={k.label} className={`kx-kpi kx-kpi--accent-${k.tone ?? 'primary'}`}>
                <span className="kx-kpi__label">{k.label}</span>
                <strong className="kx-kpi__value tnum">
                  {k.value}
                  {k.unit && <span className="kx-kpi__unit">{k.unit}</span>}
                </strong>
              </div>
            ))}
          </section>

          <div className="kx-mkt__split">
            {/* 티어 카드 */}
            <section className="kx-mkt__tiers-col" aria-label="스폰서십 패키지">
              <div className="kx-mkt__list-head">
                <h2>스폰서십 패키지</h2>
                <button type="button" className="kx-mkt__link">패키지 설정 관리</button>
              </div>
              <div className="kx-mkt__tiers">
                {view.tiers.map((t) => (
                  <TierCard key={t.id} tier={t} />
                ))}
                {view.tiers.length === 0 && (
                  <EmptyState title="등록된 패키지가 없습니다" description="스폰서십 티어를 등록하세요." />
                )}
              </div>

              <div className="kx-mkt__deadline">
                <div className="kx-mkt__deadline-info">
                  <span className="kx-mkt__deadline-icon" aria-hidden="true">
                    <IconArrowRight size={20} />
                  </span>
                  <div>
                    <h3>스폰서십 체결 일정</h3>
                    <p>주요 기업 팔로업이 필요합니다. 마감이 임박한 패키지를 우선 확인하세요.</p>
                  </div>
                </div>
                <Button variant="secondary">전체 일정 보기</Button>
              </div>
            </section>

            {/* 스폰서·이행물 관리 */}
            <aside className="kx-mkt__sponsor-col" aria-label="스폰서 관리">
              <div className="kx-card">
                <div className="kx-card__head">
                  <h2><IconStar className="kx-title-ic" size={18} />스폰서 관리</h2>
                </div>
                <ul className="kx-mkt__sponsors">
                  {sponsors.map((s) => (
                    <li key={s.id}>
                      <button
                        type="button"
                        className={`kx-mkt__sponsor ${s.id === active?.id ? 'is-selected' : ''}`}
                        aria-pressed={s.id === active?.id}
                        onClick={() => setSelectedSponsor(s.id)}
                      >
                        <span className="kx-mkt__sponsor-avatar" aria-hidden="true">{s.initial}</span>
                        <span className="kx-mkt__sponsor-info">
                          <strong>{s.name}</strong>
                          <span>{s.tier ?? '-'}</span>
                        </span>
                        <SponsorPill status={s.status} />
                      </button>
                    </li>
                  ))}
                  {sponsors.length === 0 && (
                    <li>
                      <EmptyState title="스폰서가 없습니다" description="계약된 스폰서가 여기에 표시됩니다." />
                    </li>
                  )}
                </ul>
              </div>

              {active && (
                <div className="kx-card">
                  <div className="kx-card__head">
                    <h2><IconCheckCircle className="kx-title-ic" size={18} />{active.name} 이행 현황</h2>
                  </div>
                  <ul className="kx-mkt__fulfillment">
                    {active.fulfillment.map((f) => (
                      <li key={f.id} className={f.done ? 'is-done' : ''}>
                        <span className={`kx-mkt__check ${f.done ? 'is-done' : ''}`} aria-hidden="true">
                          {f.done && <IconCheck size={14} />}
                        </span>
                        {f.label}
                      </li>
                    ))}
                    {active.fulfillment.length === 0 && (
                      <li className="kx-vis__activity-empty">이행 항목 없음</li>
                    )}
                  </ul>
                  <button type="button" className="kx-mkt__roi-link">
                    <span>노출 · 리드 · ROI 대시보드</span>
                    <IconArrowRight size={18} />
                  </button>
                </div>
              )}
            </aside>
          </div>
        </>
      )}
    </div>
  );
}

function TierCard({ tier: t }: { tier: TierDto }) {
  const sold = t.status === 'soldout';
  return (
    <div className={`kx-mkt__tier ${sold ? 'is-soldout' : ''}`} style={{ ['--tier-accent' as string]: t.accent ?? '#667085' }}>
      <div className="kx-mkt__tier-body">
        <div className="kx-mkt__tier-top">
          <span className="kx-mkt__tier-badge">{t.name}</span>
          {t.dday != null && <DdayChip dday={t.dday} />}
        </div>
        <h3 className="kx-mkt__tier-name">{t.nameKo}</h3>
        <p className="kx-mkt__tier-price tnum">{t.price}</p>
        <ul className="kx-mkt__tier-benefits">
          {t.benefits.map((b, i) => (
            <li key={i}>
              <span className="kx-mkt__tier-check" aria-hidden="true">
                <IconCheck size={16} />
              </span>
              {b}
            </li>
          ))}
        </ul>
      </div>
      <div className="kx-mkt__tier-foot">
        {sold ? (
          <>
            <span className="kx-mkt__tier-remain is-sold">판매 완료</span>
            <Button variant="secondary" disabled>종료</Button>
          </>
        ) : (
          <>
            <span className="kx-mkt__tier-remain">
              잔여 <strong className="tnum">{t.remaining}</strong>
            </span>
            <Button>선택</Button>
          </>
        )}
      </div>
    </div>
  );
}

const KNOWN_SPONSOR_STATUS: SponsorContractStatus[] = ['signed', 'pending'];
function SponsorPill({ status }: { status: string }) {
  const s = (KNOWN_SPONSOR_STATUS as string[]).includes(status) ? (status as SponsorContractStatus) : 'pending';
  return <span className={`kx-mkt__spill is-${s}`}>{SPONSOR_STATUS_LABEL[s]}</span>;
}

/** 폴백 뷰(오프라인 강등 시) — sampleMarketing 파생. */
const SAMPLE_VIEW: SponsorshipViewDto = {
  kpis: SPONSOR_KPIS.map((k) => ({ label: k.label, value: k.value, unit: k.unit ?? null, tone: k.tone ?? null })),
  tiers: SPONSOR_TIERS.map((t) => ({
    id: t.id,
    name: t.name,
    nameKo: t.nameKo,
    price: t.price,
    accent: t.accent,
    benefits: t.benefits,
    remaining: t.remaining,
    status: t.status,
    dday: t.dday ?? null,
  })),
  sponsors: SPONSORS.map<SponsorDto>((s) => ({
    id: s.id,
    name: s.name,
    initial: s.initial,
    tier: s.tier,
    status: s.status,
    fulfillment: FULFILLMENT.map((f) => ({ id: f.id, label: f.label, done: f.done })),
  })),
};

function isDegradable(error: unknown): boolean {
  return (
    error instanceof ApiRequestError &&
    (error.code === 'NETWORK' || error.code === 'NOT_FOUND' || error.code === 'NOT_IMPLEMENTED')
  );
}
