'use client';

import { useEffect, useMemo, useState } from 'react';
import type { Kuppel } from '@/types/logbuch';
import { artLabel } from '@/types/logbuch';

interface MonthlyRow {
  monat: number;
  ArtFuehrung: string;
  besucher: number;
  anzahl: number;
}

interface StatsData {
  monthly: MonthlyRow[];
  cumulative: number;
  tage: number;
  allCumulative: number;
  allTage: number;
  year: number;
  kuppel: Kuppel;
}

const MONATE = [
  'Januar','Februar','März','April','Mai','Juni',
  'Juli','August','September','Oktober','November','Dezember',
];

interface Props {
  kuppel: Kuppel;
}

export default function Statistik({ kuppel }: Props) {
  const [year, setYear] = useState(new Date().getFullYear());
  const [data, setData] = useState<StatsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    setLoading(true);
    setError('');
    fetch(`/api/statistik?kuppel=${encodeURIComponent(kuppel)}&year=${year}`)
      .then((r) => { if (!r.ok) throw new Error(); return r.json(); })
      .then((d: StatsData) => { setData(d); setLoading(false); })
      .catch(() => { setError('Fehler beim Laden der Statistik.'); setLoading(false); });
  }, [kuppel, year]);

  const { arten, matrix, monatTotal, artTotal, grandTotal, anzahlTotal } = useMemo(() => {
    if (!data) {
      return { arten: [] as string[], matrix: [] as (number | null)[][], monatTotal: [] as number[], artTotal: [] as number[], grandTotal: 0, anzahlTotal: [] as number[] };
    }

    const artenSet = new Set<string>();
    data.monthly.forEach((r) => artenSet.add(r.ArtFuehrung));
    const arten = Array.from(artenSet).sort();

    const matrix: (number | null)[][] = [];
    const monatTotal: number[] = [];
    const anzahlTotal: number[] = [];
    const artTotal: number[] = new Array(arten.length).fill(0);
    let grandTotal = 0;

    for (let m = 1; m <= 12; m++) {
      const row: (number | null)[] = [];
      let mSum = 0;
      let aSum = 0;
      arten.forEach((art, idx) => {
        const found = data.monthly.find((r) => r.monat === m && r.ArtFuehrung === art);
        const val = found ? found.besucher : null;
        row.push(val);
        if (val !== null) {
          mSum += val;
          artTotal[idx] += val;
          aSum += found!.anzahl;
        }
      });
      matrix.push(row);
      monatTotal.push(mSum);
      anzahlTotal.push(aSum);
      grandTotal += mSum;
    }

    return { arten, matrix, monatTotal, artTotal, grandTotal, anzahlTotal };
  }, [data]);

  if (loading) return <div className="text-gray-500 text-sm py-4">Lade Statistik...</div>;
  if (error)   return <div className="text-red-600 text-sm py-4">{error}</div>;

  const headCls = 'px-3 py-2 border border-gray-300 text-xs font-semibold bg-gray-100 whitespace-nowrap';
  const cellCls = 'px-3 py-2 border border-gray-200 text-sm text-right tabular-nums';
  const labelCls = 'px-3 py-2 border border-gray-200 text-sm text-left whitespace-nowrap';

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3 print:hidden">
        <label className="text-sm font-medium text-gray-700">Jahr</label>
        <input
          type="number"
          value={year}
          onChange={(e) => setYear(parseInt(e.target.value, 10) || new Date().getFullYear())}
          min={2000}
          max={2100}
          className="w-24 px-2 py-1 border-2 border-gray-400 rounded-lg bg-white text-sm focus:border-blue-500 focus:outline-none"
        />
      </div>

      <div className="overflow-x-auto">
        <table className="w-full border-collapse text-sm">
          <thead>
            <tr>
              <th className={headCls}>Monat</th>
              <th className={headCls}>Führungen</th>
              {arten.map((art) => (
                <th key={art} className={headCls}>{artLabel(art as any) || art}</th>
              ))}
              <th className={headCls}>Gesamt</th>
            </tr>
          </thead>
          <tbody>
            {MONATE.map((name, idx) => {
              const mSum = monatTotal[idx];
              const aSum = anzahlTotal[idx];
              return (
                <tr key={name} className={mSum > 0 ? '' : 'text-gray-400'}>
                  <td className={labelCls}>{name}</td>
                  <td className={cellCls}>{aSum > 0 ? aSum : ''}</td>
                  {arten.map((_, aIdx) => {
                    const val = matrix[idx][aIdx];
                    return (
                      <td key={aIdx} className={cellCls}>
                        {val !== null && val > 0 ? val.toLocaleString('de-DE') : ''}
                      </td>
                    );
                  })}
                  <td className={`${cellCls} font-semibold`}>{mSum > 0 ? mSum.toLocaleString('de-DE') : ''}</td>
                </tr>
              );
            })}
            <tr className="bg-gray-50 font-semibold">
              <td className={labelCls}>Summe</td>
              <td className={cellCls}>{anzahlTotal.reduce((s, v) => s + v, 0) > 0 ? anzahlTotal.reduce((s, v) => s + v, 0).toLocaleString('de-DE') : ''}</td>
              {artTotal.map((t, i) => (
                <td key={i} className={cellCls}>{t > 0 ? t.toLocaleString('de-DE') : ''}</td>
              ))}
              <td className={cellCls}>{grandTotal > 0 ? grandTotal.toLocaleString('de-DE') : ''}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 w-full">
        <div className="border-2 border-gray-300 rounded-xl p-4 bg-white">
          <div className="text-xs text-gray-500 mb-1">Kumulierte Besucher {year} ({data?.kuppel})</div>
          <div className="text-2xl font-bold">{data?.cumulative.toLocaleString('de-DE') ?? 0}</div>
        </div>
        <div className="border-2 border-gray-300 rounded-xl p-4 bg-white">
          <div className="text-xs text-gray-500 mb-1">Führungstage {year} ({data?.kuppel})</div>
          <div className="text-2xl font-bold">{data?.tage ?? 0}</div>
        </div>
        <div className="border-2 border-green-600 rounded-xl p-4 bg-green-50">
          <div className="text-xs text-green-700 mb-1">Kumulierte Besucher {year} (Sternwarte gesamt)</div>
          <div className="text-2xl font-bold text-green-800">{data?.allCumulative.toLocaleString('de-DE') ?? 0}</div>
        </div>
        <div className="border-2 border-green-600 rounded-xl p-4 bg-green-50">
          <div className="text-xs text-green-700 mb-1">Führungstage {year} (Sternwarte gesamt)</div>
          <div className="text-2xl font-bold text-green-800">{data?.allTage ?? 0}</div>
        </div>
      </div>
    </div>
  );
}
