/*
 * SCR-22 서류·마일스톤 워크플로 [M6]. Stitch scr_22_docs_milestones 이식.
 * 진입: 주최자 대시보드 마일스톤 노드 / 사이드바 "서류·마일스톤" (design.md §3 SCR-22).
 * 구성: ①상단 마일스톤 진행 바(D-150→D-0) ②좌 신고서류 체크리스트(상태·D-데이·액션)
 *       ③우 AI 서류 검수 카드(불일치·누락·kxwp 안내) + 전체 공정률.
 * ★ 실 API 배선(useQuery, 로딩/빈/에러 3상태) — GET /milestones · /documents · /documents/review.
 *   HWP/PDF 생성은 파일 큐 후속 → 해당 버튼 disabled + 툴팁 유지.
 */
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { AiLabel, DdayChip, StatusBadge, type FlowStatus } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import {
  IconCheck,
  IconDocument,
  IconSpark,
  IconTrendUp,
  IconWarning,
} from '../../components/ui/icons';
import { useResolvedEventId } from '../../hooks/useResolvedEventId';
import { docsApi, type RequiredDocRow } from './docsApi';
import './docs.css';

type DocAction = 'view' | 'hwp' | 'write' | 'fix';

const ACTION_LABEL: Record<DocAction, string> = {
  view: '보기',
  hwp: 'HWP 생성',
  write: '작성',
  fix: '수정',
};

const RENDER_TOOLTIP = 'HWP/PDF 생성은 파일 큐 연동 후속(준비중)';

/** 서류 상태 → 리스트 액션 파생. pending 은 액션 없음(준비중 표기). */
function actionFor(status: RequiredDocRow['status']): DocAction | undefined {
  switch (status) {
    case 'approved':
      return 'view';
    case 'submitted':
      return 'hwp';
    case 'draft':
      return 'write';
    case 'rejected':
      return 'fix';
    default:
      return undefined;
  }
}

/**
 * SCR-22 서류·마일스톤 워크플로 페이지.
 * onOpenAuthoring: [작성] 클릭 시 SCR-23 신고서류 작성으로 이동(라우팅은 App 소관 — 미주입 시 토스트).
 */
export function DocsMilestonePage({ onOpenAuthoring }: { onOpenAuthoring?: (docType: string) => void }) {
  const eventId = useResolvedEventId();
  const [toast, setToast] = useState<string | null>(null);

  const milestonesQ = useQuery({
    queryKey: ['docs-milestones', eventId],
    queryFn: () => docsApi.milestones(eventId as string),
    enabled: !!eventId,
    retry: false,
  });
  const docsQ = useQuery({
    queryKey: ['docs-documents', eventId],
    queryFn: () => docsApi.documents(eventId as string),
    enabled: !!eventId,
    retry: false,
  });
  const reviewQ = useQuery({
    queryKey: ['docs-review', eventId],
    queryFn: () => docsApi.review(eventId as string),
    enabled: !!eventId,
    retry: false,
  });

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2200);
    return () => clearTimeout(t);
  }, [toast]);

  const milestones = milestonesQ.data ?? [];
  const nextDday = useMemo(() => {
    const active = milestones.find((m) => m.state === 'active') ?? milestones.find((m) => m.state === 'todo');
    return active?.dueDate ? daysUntil(active.dueDate) : null;
  }, [milestones]);

  function handleAction(doc: RequiredDocRow, action: DocAction) {
    if (action === 'write' || action === 'fix') {
      if (onOpenAuthoring) onOpenAuthoring(doc.docType);
      else setToast(`${doc.name} 작성 화면(SCR-23)으로 이동`);
      return;
    }
    if (action === 'view') {
      setToast(`${doc.name} · 보기`);
    }
  }

  const activeIdx = milestones.findIndex((m) => m.state === 'active');
  const fillPct = activeIdx <= 0 ? 0 : (activeIdx / (milestones.length - 1)) * 100;

  const listStatus: 'loading' | 'error' | 'success' = docsQ.isPending
    ? 'loading'
    : docsQ.isError
      ? 'error'
      : 'success';
  const docs = docsQ.data ?? [];

  return (
    <div className="kx-page">
      <header className="kx-doc__head">
        <div>
          <h1 className="kx-doc__title">서류·마일스톤</h1>
          <p className="kx-doc__subtitle">신고서류 준비 현황 · AI 서류 검수</p>
        </div>
      </header>

      {/* 마일스톤 진행 바 */}
      <section className="kx-card" aria-label="전시 마일스톤 현황">
        <div className="kx-doc__miles-head">
          <span className="kx-doc__miles-title">
            <IconDocument size={18} /> 전시 마일스톤 현황
          </span>
          {nextDday != null && nextDday >= 0 && <DdayChip dday={nextDday} />}
        </div>
        {milestonesQ.isPending ? (
          <Skeleton height={72} />
        ) : milestones.length === 0 ? (
          <EmptyState
            title="구성된 마일스톤이 없습니다"
            description="행사를 생성하면 마일스톤이 자동 구성됩니다."
          />
        ) : (
          <div className="kx-doc__stepper">
            <span className="kx-doc__track" aria-hidden="true" />
            <span
              className="kx-doc__track-fill"
              aria-hidden="true"
              style={{ width: `calc((100% - var(--space-5) * 2) * ${fillPct / 100})` }}
            />
            {milestones.map((m) => (
              <div key={m.label} className={`kx-doc__step is-${m.state}`}>
                <span className="kx-doc__node">
                  {m.state === 'done' ? (
                    <IconCheck size={20} />
                  ) : (
                    <span className="tnum" aria-hidden="true">
                      {m.state === 'active' ? '⏳' : '·'}
                    </span>
                  )}
                </span>
                <span className="kx-doc__step-label">{m.label}</span>
                <span className="kx-doc__step-sub">{m.sub}</span>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* 서류 리스트 3상태 */}
      {listStatus === 'loading' && (
        <div className="kx-doc__grid" aria-busy="true">
          <section className="kx-card">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} style={{ padding: '12px 0' }}>
                <Skeleton height={22} />
              </div>
            ))}
          </section>
          <section className="kx-card">
            <Skeleton height={120} />
          </section>
        </div>
      )}

      {listStatus === 'error' && (
        <ErrorState message="서류 현황을 불러오지 못했습니다." onRetry={() => docsQ.refetch()} />
      )}

      {listStatus === 'success' && (
        <div className="kx-doc__grid">
          {/* 신고서류 체크리스트 */}
          <section className="kx-card kx-doc__list" aria-label="신고서류 체크리스트">
            <div className="kx-doc__list-head">
              <div>
                <h2><IconDocument className="kx-title-ic" size={18} />신고서류 체크리스트</h2>
                <p>전시회 개최를 위한 필수 서류 목록 및 승인 현황</p>
              </div>
              <ChecklistProgress docs={docs} />
            </div>

            {docs.length === 0 ? (
              <EmptyState
                title="구성된 서류가 없습니다"
                description="행사를 생성하면 마일스톤·서류가 자동 구성됩니다."
              />
            ) : (
              docs.map((doc) => <DocRow key={doc.docType} doc={doc} onAction={handleAction} />)
            )}
          </section>

          {/* 우측 — AI 서류 검수 + 공정률 */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
            <section className="kx-doc__ai" aria-label="AI 서류 검수">
              <div className="kx-doc__ai-head">
                <IconSpark size={18} />
                <h2>AI 서류 검수</h2>
                <AiLabel>AI 검수</AiLabel>
              </div>
              {reviewQ.isPending ? (
                <Skeleton height={96} />
              ) : (reviewQ.data?.issues ?? []).length === 0 ? (
                <p className="kx-doc__issue-desc">검출된 불일치·누락이 없습니다.</p>
              ) : (
                (reviewQ.data?.issues ?? []).map((iss) => (
                  <div key={iss.title} className={`kx-doc__issue kx-doc__issue--${iss.tone}`}>
                    <span className="kx-doc__issue-icon" aria-hidden="true">
                      <IconWarning size={18} />
                    </span>
                    <div>
                      <p className="kx-doc__issue-title">{iss.title}</p>
                      <p className="kx-doc__issue-desc">{iss.description}</p>
                    </div>
                  </div>
                ))
              )}
              <div className="kx-doc__note">
                <p className="kx-doc__note-title">
                  <IconDocument size={14} /> kxwp 제출 안내
                </p>
                <p className="kx-doc__note-body">
                  작성 데이터를 기반으로 공문서 표준 서식(HWP/PDF)을 즉시 생성한 뒤, kxwp 시스템에
                  수동 업로드하는 방식입니다.
                </p>
              </div>
              <Button
                variant="ai"
                block
                leadingIcon={<IconSpark size={16} />}
                disabled
                title={RENDER_TOOLTIP}
              >
                자동 문서 생성하기
              </Button>
            </section>

            <section className="kx-doc__stat" aria-label="전체 공정률">
              <p className="kx-doc__stat-label">전체 공정률</p>
              <p className="kx-doc__stat-value tnum">
                {reviewQ.isPending ? '—' : `${reviewQ.data?.progressPct ?? 0}%`}
              </p>
              <p className="kx-doc__stat-delta">
                <IconTrendUp size={16} /> 준비중 제외 진척 기준
              </p>
            </section>
          </div>
        </div>
      )}

      {toast && (
        <div className="kx-doc__toast" role="status">
          {toast}
        </div>
      )}
    </div>
  );
}

/** 준비중(pending) 제외한 진척 집계. */
function ChecklistProgress({ docs }: { docs: RequiredDocRow[] }) {
  const total = docs.length;
  const done = docs.filter((d) => d.status !== 'pending').length;
  const pct = total ? Math.round((done / total) * 100) : 0;
  return (
    <div className="kx-doc__progress">
      <span className="kx-doc__progress-num tnum">
        {done}/{total} 완료
      </span>
      <span className="kx-doc__progress-track" aria-hidden="true">
        <span className="kx-doc__progress-fill" style={{ width: `${pct}%` }} />
      </span>
    </div>
  );
}

function DocRow({
  doc,
  onAction,
}: {
  doc: RequiredDocRow;
  onAction: (d: RequiredDocRow, action: DocAction) => void;
}) {
  const isPending = doc.status === 'pending';
  const action = actionFor(doc.status);
  const rowCls = [
    'kx-doc__row',
    action === 'write' ? 'kx-doc__row--active' : '',
    isPending ? 'kx-doc__row--muted' : '',
  ]
    .filter(Boolean)
    .join(' ');

  const btnVariant =
    action === 'write' ? 'primary' : action === 'fix' ? 'danger' : 'secondary';
  // HWP/PDF 렌더 액션은 파일 큐 후속 → 비활성(툴팁).
  const isRenderAction = action === 'hwp';

  return (
    <div className={rowCls}>
      <div className="kx-doc__row-main">
        <span className="kx-doc__doc-icon" aria-hidden="true">
          <IconDocument size={18} />
        </span>
        <span className="kx-doc__doc-name">{doc.name}</span>
        {doc.dday != null && <DdayChip dday={doc.dday} />}
      </div>
      <div className="kx-doc__row-actions">
        {isPending ? (
          <span className="kx-doc__pill-pending">준비중</span>
        ) : (
          <StatusBadge status={doc.status as FlowStatus} />
        )}
        {action && (
          <Button
            variant={btnVariant}
            disabled={isRenderAction}
            title={isRenderAction ? RENDER_TOOLTIP : undefined}
            onClick={() => (isRenderAction ? undefined : onAction(doc, action))}
          >
            {ACTION_LABEL[action]}
          </Button>
        )}
      </div>
    </div>
  );
}

/** dueDate(YYYY-MM-DD)까지 남은 일수(음수 허용). */
function daysUntil(dateStr: string): number {
  const due = new Date(`${dateStr}T00:00:00`);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return Math.round((due.getTime() - today.getTime()) / 86_400_000);
}
