/*
 * SCR-46 업무보고·통계 (report + stats). 참조: UIWS report/*·stats/*.
 * 기간 탭(일/주/월/분기/연) + 요약 KPI + 유형별 차트 + 작성자별 표 + 최근 보고서 목록.
 * 백엔드: /api/work/stats/worklog(fromDate·toDate 집계), /api/work/reports(문서).
 * ★ 갭: 보고서 Jasper PDF 출력 엔드포인트 부재 → PDF 버튼 disabled. 07_work_api_gaps.md 기록.
 */
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { reportApi, workStatsApi } from '../../api/endpoints';
import { Button } from '../../components/ui/Button';
import { CHART } from '../chartColors';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconAnalytics, IconDocument, IconDownload, IconUsers } from '../../components/ui/icons';
import { errMessage, fmtDate } from './workShared';
import './work.css';

type Period = 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'QUARTERLY' | 'YEARLY';
const PERIODS: { v: Period; l: string }[] = [
  { v: 'DAILY', l: '일간' },
  { v: 'WEEKLY', l: '주간' },
  { v: 'MONTHLY', l: '월간' },
  { v: 'QUARTERLY', l: '분기' },
  { v: 'YEARLY', l: '연간' },
];
const BAR_COLORS = [CHART.primary600, CHART.primary700, CHART.aiAccent, CHART.success, CHART.violationWarn, CHART.slate];

function iso(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
/** 기간 → [fromDate, toDate] (역년/ISO 주 기준, 화면 편의 산출). */
function periodRange(p: Period): [string, string] {
  const now = new Date();
  const y = now.getFullYear();
  if (p === 'DAILY') return [iso(now), iso(now)];
  if (p === 'WEEKLY') {
    const day = now.getDay();
    const mon = new Date(now);
    mon.setDate(now.getDate() - ((day + 6) % 7));
    const sun = new Date(mon);
    sun.setDate(mon.getDate() + 6);
    return [iso(mon), iso(sun)];
  }
  if (p === 'MONTHLY') return [iso(new Date(y, now.getMonth(), 1)), iso(new Date(y, now.getMonth() + 1, 0))];
  if (p === 'QUARTERLY') {
    const q = Math.floor(now.getMonth() / 3);
    return [iso(new Date(y, q * 3, 1)), iso(new Date(y, q * 3 + 3, 0))];
  }
  return [iso(new Date(y, 0, 1)), iso(new Date(y, 11, 31))];
}

export function ReportPage() {
  const [period, setPeriod] = useState<Period>('WEEKLY');
  const [from, to] = useMemo(() => periodRange(period), [period]);

  const statsQ = useQuery({
    queryKey: ['work-stats', from, to],
    queryFn: () => workStatsApi.worklog({ fromDate: from, toDate: to }),
  });
  const reportsQ = useQuery({
    queryKey: ['reports'],
    queryFn: () => reportApi.list({ page: 0, size: 20 }),
  });

  const stats = statsQ.data;

  return (
    <div className="kx-page">
      <header className="kx-work__head">
        <div>
          <h1 className="kx-work__title">업무보고·통계</h1>
          <p className="kx-work__subtitle">
            일상 업무보고 집계 ({from.replace(/-/g, '.')} ~ {to.replace(/-/g, '.')})
          </p>
        </div>
        <div className="kx-work__head-actions">
          <div className="kx-seg" role="tablist" aria-label="기간">
            {PERIODS.map((p) => (
              <button
                key={p.v}
                role="tab"
                aria-selected={period === p.v}
                className={`kx-seg__btn ${period === p.v ? 'is-active' : ''}`}
                onClick={() => setPeriod(p.v)}
              >
                {p.l}
              </button>
            ))}
          </div>
          <span title="백엔드 미지원 — Jasper PDF 연동 후 활성화" style={{ display: 'inline-flex' }}>
            <Button variant="secondary" disabled leadingIcon={<IconDownload size={16} />}>
              보고서 PDF
            </Button>
          </span>
        </div>
      </header>

      {/* KPI */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <div className="kx-kpi">
          <span className="kx-kpi__label">총 업무 건수</span>
          <span className="kx-kpi__value tnum">
            {statsQ.isLoading ? <Skeleton height={28} width={80} /> : (stats?.totalCount ?? 0)}
          </span>
        </div>
        <div className="kx-kpi">
          <span className="kx-kpi__label">총 공수(시간)</span>
          <span className="kx-kpi__value tnum">
            {statsQ.isLoading ? <Skeleton height={28} width={80} /> : (stats?.totalHours ?? 0)}
          </span>
        </div>
        <div className="kx-kpi">
          <span className="kx-kpi__label">참여 작성자</span>
          <span className="kx-kpi__value tnum">
            {statsQ.isLoading ? <Skeleton height={28} width={80} /> : (stats?.byWriter.length ?? 0)}
          </span>
        </div>
      </div>

      {statsQ.isError && (
        <ErrorState message={errMessage(statsQ.error)} onRetry={() => statsQ.refetch()} />
      )}

      {/* 유형별 차트 */}
      <section className="kx-card" aria-label="유형별 업무량">
        <div className="kx-card__head">
          <h2><IconAnalytics className="kx-title-ic" size={18} />유형별 업무량</h2>
        </div>
        {statsQ.isLoading ? (
          <Skeleton height={260} />
        ) : !stats || stats.byType.length === 0 ? (
          <EmptyState title="집계할 데이터가 없습니다" description="선택 기간에 등록된 업무일지가 없습니다." />
        ) : (
          <div style={{ width: '100%', height: 280 }}>
            <ResponsiveContainer>
              <BarChart data={stats.byType} margin={{ top: 8, right: 8, bottom: 8, left: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke={CHART.neutral100} vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 12, fill: CHART.slate }} />
                <YAxis tick={{ fontSize: 12, fill: CHART.slate }} allowDecimals={false} />
                <Tooltip
                  contentStyle={{ fontSize: 12, borderRadius: 8, border: `1px solid ${CHART.neutral200}` }}
                  formatter={(v) => [`${Number(v ?? 0)}건`, '건수']}
                />
                <Bar dataKey="count" radius={[4, 4, 0, 0]}>
                  {stats.byType.map((_, i) => (
                    <Cell key={i} fill={BAR_COLORS[i % BAR_COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        )}
      </section>

      {/* 작성자별 표 + 최근 보고서 */}
      <div className="kx-split" style={{ gridTemplateColumns: '1fr 1fr' }}>
        <section className="kx-card" aria-label="작성자별 집계">
          <div className="kx-card__head">
            <h2><IconUsers className="kx-title-ic" size={18} />작성자별 집계</h2>
          </div>
          <div className="kx-table-scroll">
            <table className="kx-list-table">
              <thead>
                <tr>
                  <th>작성자</th>
                  <th className="kx-num" style={{ width: 80 }}>
                    건수
                  </th>
                  <th className="kx-num" style={{ width: 90 }}>
                    공수(h)
                  </th>
                </tr>
              </thead>
              <tbody>
                {statsQ.isLoading &&
                  Array.from({ length: 4 }).map((_, i) => (
                    <tr key={i}>
                      <td colSpan={3}>
                        <Skeleton height={20} />
                      </td>
                    </tr>
                  ))}
                {!statsQ.isLoading &&
                  (stats?.byWriter ?? []).map((w) => (
                    <tr key={w.name} style={{ cursor: 'default' }}>
                      <td className="kx-list-table__title">{w.name}</td>
                      <td className="kx-num">{w.count}</td>
                      <td className="kx-num">{w.hours}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
          {!statsQ.isLoading && (stats?.byWriter.length ?? 0) === 0 && (
            <EmptyState title="집계 데이터 없음" />
          )}
        </section>

        <section className="kx-card" aria-label="최근 보고서">
          <div className="kx-card__head">
            <h2><IconDocument className="kx-title-ic" size={18} />최근 업무보고</h2>
          </div>
          <div className="kx-table-scroll">
            <table className="kx-list-table">
              <thead>
                <tr>
                  <th>제목</th>
                  <th style={{ width: 80 }}>유형</th>
                  <th style={{ width: 90 }}>작성일</th>
                </tr>
              </thead>
              <tbody>
                {reportsQ.isLoading &&
                  Array.from({ length: 4 }).map((_, i) => (
                    <tr key={i}>
                      <td colSpan={3}>
                        <Skeleton height={20} />
                      </td>
                    </tr>
                  ))}
                {!reportsQ.isLoading &&
                  (reportsQ.data?.items ?? []).map((r) => (
                    <tr key={r.id} style={{ cursor: 'default' }}>
                      <td className="kx-list-table__title">{r.title}</td>
                      <td className="kx-list-table__muted">{r.reportType}</td>
                      <td className="kx-list-table__muted kx-num">{fmtDate(r.createdAt)}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
          {reportsQ.isError && (
            <ErrorState message={errMessage(reportsQ.error)} onRetry={() => reportsQ.refetch()} />
          )}
          {!reportsQ.isLoading && !reportsQ.isError && (reportsQ.data?.items.length ?? 0) === 0 && (
            <EmptyState title="작성된 보고서가 없습니다" />
          )}
        </section>
      </div>
    </div>
  );
}
