import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Line,
  LineChart,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { exhibitionApi } from '../../api/endpoints';
import type { ExhibitionDto } from '../../api/types';
import { ErrorState, Skeleton } from '../../components/ui/States';
import { homeApi } from './homeApi';

/**
 * SCR-HOME 요약 차트(소유자 지시 ④) — WISE 대시보드 스타일 Recharts 위젯.
 * 신규 백엔드 계약 없이 기존 exhibitionApi.list() + home/hall-centers 데이터에서 파생(경계면 무결).
 * 3종: ① 전시 상태 도넛 ② 월별 전시 추이 미니 라인 ③ 전시장별 행사 수 바.
 */

const TODAY = new Date();
function ymd(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
const TODAY_YMD = ymd(TODAY);

type Status = 'ongoing' | 'upcoming' | 'ended';
function statusOf(start: string, end: string): Status {
  if (end < TODAY_YMD) return 'ended';
  if (start > TODAY_YMD) return 'upcoming';
  return 'ongoing';
}
function matchesCenter(hallLabel: string | null | undefined, code: string): boolean {
  if (!hallLabel) return false;
  return new RegExp(`제\\s*${code}\\s*전시장`).test(hallLabel);
}

const C = {
  ongoing: 'var(--color-success)',
  upcoming: 'var(--color-primary-600)',
  ended: 'var(--color-neutral-500)',
  grid: 'var(--color-neutral-200)',
  axis: 'var(--color-neutral-500)',
  bar: 'var(--color-primary-600)',
  line: 'var(--color-ai-accent)',
};

export function HomeCharts() {
  const { t } = useTranslation();
  const eventsQuery = useQuery({
    queryKey: ['home-charts-events'],
    queryFn: () => exhibitionApi.list(),
  });
  const centersQuery = useQuery({
    queryKey: ['home-hall-centers'],
    queryFn: () => homeApi.hallCenters(),
  });

  const rows: ExhibitionDto[] = eventsQuery.data ?? [];

  // ① 상태 분포
  const statusData = useMemo(() => {
    const c = { ongoing: 0, upcoming: 0, ended: 0 };
    rows.forEach((e) => {
      c[statusOf(e.startDate, e.endDate)] += 1;
    });
    return [
      { key: 'ongoing', name: t('home.calendar.legendOngoing'), value: c.ongoing, color: C.ongoing },
      { key: 'upcoming', name: t('home.calendar.legendUpcoming'), value: c.upcoming, color: C.upcoming },
      { key: 'ended', name: t('home.calendar.legendEnded'), value: c.ended, color: C.ended },
    ].filter((d) => d.value > 0);
  }, [rows, t]);

  // ② 월별 추이 — 현재 달 기준 -1 ~ +4 (6개월)
  const trendData = useMemo(() => {
    const base = new Date(TODAY.getFullYear(), TODAY.getMonth() - 1, 1);
    const buckets: { ym: string; label: string; count: number }[] = [];
    for (let i = 0; i < 6; i++) {
      const d = new Date(base.getFullYear(), base.getMonth() + i, 1);
      const ym = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      buckets.push({ ym, label: `${d.getMonth() + 1}${t('home.charts.monthSuffix')}`, count: 0 });
    }
    rows.forEach((e) => {
      const ym = (e.startDate ?? '').slice(0, 7);
      const b = buckets.find((x) => x.ym === ym);
      if (b) b.count += 1;
    });
    return buckets;
  }, [rows, t]);

  // ③ 전시장별 행사 수
  const centerData = useMemo(() => {
    const centers = centersQuery.data ?? [];
    return centers.map((c) => ({
      name: c.label,
      count: rows.filter((e) => matchesCenter(e.hallLabel, c.code)).length,
    }));
  }, [rows, centersQuery.data]);

  const loading = eventsQuery.isLoading;
  const error = eventsQuery.isError;

  return (
    <section className="kx-card kx-home__charts" aria-label={t('home.charts.title')}>
      <div className="kx-home__widget-head">
        <h2>{t('home.charts.title')}</h2>
      </div>

      {loading ? (
        <div className="kx-home__charts-grid">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} height={150} radius={8} />
          ))}
        </div>
      ) : error ? (
        <ErrorState message={t('home.loadError')} onRetry={() => eventsQuery.refetch()} />
      ) : (
        <div className="kx-home__charts-grid">
          {/* ① 상태 도넛 */}
          <figure className="kx-home__chart">
            <figcaption className="kx-home__chart-cap">{t('home.charts.statusTitle')}</figcaption>
            {statusData.length === 0 ? (
              <p className="kx-home__chart-empty">{t('home.charts.empty')}</p>
            ) : (
              <ResponsiveContainer width="100%" height={150}>
                <PieChart>
                  <Pie
                    data={statusData}
                    dataKey="value"
                    nameKey="name"
                    innerRadius={38}
                    outerRadius={58}
                    paddingAngle={2}
                    strokeWidth={0}
                  >
                    {statusData.map((d) => (
                      <Cell key={d.key} fill={d.color} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            )}
            <div className="kx-home__chart-legend">
              {statusData.map((d) => (
                <span key={d.key} className="kx-home__chart-legend-item">
                  <i style={{ background: d.color }} />
                  {d.name} <b className="tnum">{d.value}</b>
                </span>
              ))}
            </div>
          </figure>

          {/* ② 월별 추이 미니 라인 */}
          <figure className="kx-home__chart">
            <figcaption className="kx-home__chart-cap">{t('home.charts.trendTitle')}</figcaption>
            <ResponsiveContainer width="100%" height={150}>
              <LineChart data={trendData} margin={{ top: 8, right: 8, bottom: 0, left: -20 }}>
                <CartesianGrid strokeDasharray="3 3" stroke={C.grid} vertical={false} />
                <XAxis dataKey="label" tick={{ fontSize: 11, fill: C.axis }} axisLine={false} tickLine={false} />
                <YAxis allowDecimals={false} tick={{ fontSize: 11, fill: C.axis }} axisLine={false} tickLine={false} width={28} />
                <Tooltip />
                <Line type="monotone" dataKey="count" stroke={C.line} strokeWidth={2} dot={{ r: 3 }} activeDot={{ r: 5 }} />
              </LineChart>
            </ResponsiveContainer>
          </figure>

          {/* ③ 전시장별 바 */}
          <figure className="kx-home__chart">
            <figcaption className="kx-home__chart-cap">{t('home.charts.centerTitle')}</figcaption>
            {centerData.length === 0 ? (
              <p className="kx-home__chart-empty">{t('home.charts.empty')}</p>
            ) : (
              <ResponsiveContainer width="100%" height={150}>
                <BarChart data={centerData} margin={{ top: 8, right: 8, bottom: 0, left: -20 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke={C.grid} vertical={false} />
                  <XAxis dataKey="name" tick={{ fontSize: 11, fill: C.axis }} axisLine={false} tickLine={false} />
                  <YAxis allowDecimals={false} tick={{ fontSize: 11, fill: C.axis }} axisLine={false} tickLine={false} width={28} />
                  <Tooltip />
                  <Bar dataKey="count" fill={C.bar} radius={[3, 3, 0, 0]} maxBarSize={40} />
                </BarChart>
              </ResponsiveContainer>
            )}
          </figure>
        </div>
      )}
    </section>
  );
}
