'use client';

import { useState, useEffect, useCallback } from 'react';
import AppLayout from '@/components/AppLayout';
import BarChart from '@/components/BarChart';
import { VerbrauchPoint, Every, RangeKey } from '@/types/strom';

const COLOR_24H = '#2980b9';
const COLOR_7D = '#27ae60';
const COLOR_31D = '#e67e22';
const COLOR_365D = '#8e44ad';

type SelectorKind = 'date24' | 'date' | 'month' | 'year';

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

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

const CURRENT_YEAR = new Date().getFullYear();
const YEARS = Array.from({ length: 11 }, (_, i) => CURRENT_YEAR - i);

interface ChartCardProps {
  range: RangeKey;
  every: Every;
  title: string;
  color: string;
  selector: SelectorKind;
}

function ChartCard({ range, every, title, color, selector }: ChartCardProps) {
  const [value, setValue] = useState<string>(() => {
    switch (selector) {
      case 'date24':
        return ''; // leer = rollierend letzte 24h
      case 'date':
        return todayStr();
      case 'month':
        return thisMonthStr();
      case 'year':
        return String(CURRENT_YEAR);
    }
  });
  const [data, setData] = useState<VerbrauchPoint[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // E-Auto-Ladetage (nur 31d): werden asynchron nachgeladen
  const [ladeDays, setLadeDays] = useState<Set<number>>(new Set());
  const [ladeLoading, setLadeLoading] = useState(false);
  const [ladeMeta, setLadeMeta] = useState<{ thresholdKw: number; minHours: number } | null>(null);

  const fetchLaden = useCallback(
    async (sel: string) => {
      if (range !== '31d') return;
      setLadeLoading(true);
      setLadeDays(new Set());
      try {
        const res = await fetch(`/api/laden?month=${sel}`, { cache: 'no-store' });
        const json = await res.json();
        if (json.success) {
          setLadeDays(new Set<number>(json.days));
          setLadeMeta({ thresholdKw: json.thresholdKw, minHours: json.minHours });
        }
      } catch {
        // Markierung ist sekundaer -> Fehler still ignorieren
      } finally {
        setLadeLoading(false);
      }
    },
    [range]
  );

  const fetchData = useCallback(
    async (sel: string) => {
      setIsLoading(true);
      setError(null);
      try {
        const params = new URLSearchParams({ range });
        if (selector === 'date24' && sel) params.set('date', sel);
        if (selector === 'date') params.set('date', sel);
        if (selector === 'month') params.set('month', sel);
        if (selector === 'year') params.set('year', sel);

        const res = await fetch(`/api/verbrauch?${params.toString()}`, {
          cache: 'no-store',
          headers: { 'Cache-Control': 'no-cache' },
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        if (json.success) {
          setData(json.data);
        } else {
          setError(json.error || 'Fehler beim Laden der Daten.');
        }
      } catch {
        setError('Netzwerkfehler.');
      } finally {
        setIsLoading(false);
      }
    },
    [range, selector]
  );

  useEffect(() => {
    fetchData(value);
    fetchLaden(value);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleApply = () => {
    fetchData(value);
    fetchLaden(value);
  };

  // Jahres-Chart: Achse immer ueber das komplette Kalenderjahr -> alle 12 Monate
  // sichtbar, Restmonate bleiben ohne Balken.
  let xMin: number | undefined;
  let xMax: number | undefined;
  if (range === '365d') {
    const y = Number(value);
    if (Number.isFinite(y)) {
      xMin = new Date(y, 0, 1).getTime();
      // bis Ende Dezember -> Januar des Folgejahres wird nicht mehr angezeigt
      xMax = new Date(y + 1, 0, 1).getTime() - 1;
    }
  }

  // Gesamtverbrauch des angezeigten Zeitraums
  const total = data.reduce((sum, [, v]) => sum + v, 0);
  const totalLabel = range === '365d' ? `Gesamtverbrauch ${value}` : 'Gesamtverbrauch';

  return (
    <div className="block w-full bg-white border border-black rounded-lg shadow-md p-3 overflow-hidden mb-6">
      {/* Steuerung */}
      <div className="flex flex-wrap gap-4 items-end mb-3 px-1">
        <div className="flex flex-row items-center gap-2">
          <label className="font-semibold whitespace-nowrap text-sm">
            {selector === 'date24' && 'Tag (leer = letzte 24h):'}
            {selector === 'date' && 'Tag:'}
            {selector === 'month' && 'Monat:'}
            {selector === 'year' && 'Jahr:'}
          </label>

          {selector === 'year' ? (
            <select
              value={value}
              onChange={(e) => setValue(e.target.value)}
              className="border border-gray-400 rounded px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-gray-500"
            >
              {YEARS.map((y) => (
                <option key={y} value={y}>
                  {y}
                </option>
              ))}
            </select>
          ) : (
            <input
              type={selector === 'month' ? 'month' : 'date'}
              value={value}
              onChange={(e) => setValue(e.target.value)}
              className="border border-gray-400 rounded px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-gray-500"
            />
          )}
        </div>

        <button
          onClick={handleApply}
          disabled={isLoading}
          className="bg-[#85B7D7] hover:bg-[#6a9fc5] px-5 py-2 text-sm rounded-lg transition-colors shadow-md disabled:opacity-50"
        >
          {isLoading ? 'Lade...' : 'Anzeigen'}
        </button>

        {error && <span className="text-red-600 text-sm">{error}</span>}
        {!isLoading && !error && data.length === 0 && (
          <span className="text-gray-500 text-sm">Keine Daten im gewählten Zeitraum.</span>
        )}
      </div>

      {/* Diagramm */}
      {isLoading ? (
        <div className="text-center py-16 text-gray-500">Lade Daten…</div>
      ) : (
        <>
          <BarChart
            title={title}
            data={data}
            every={every}
            color={color}
            xMin={xMin}
            xMax={xMax}
            highlight={range === '31d' ? ladeDays : undefined}
          />
          <div className="flex justify-between items-center mt-2 px-2 text-sm">
            {/* Legende: E-Auto-Ladetage (nur 31d) */}
            {range === '31d' ? (
              <span className="text-gray-600 flex items-center gap-1.5">
                <span className="inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: '#c0392b' }} />
                {ladeLoading
                  ? 'E-Auto-Ladung wird geprüft…'
                  : ladeDays.size > 0
                    ? `E-Auto geladen (> ${ladeMeta?.thresholdKw ?? ''} kW, ≥ ${ladeMeta?.minHours ?? ''} h)`
                    : 'Keine E-Auto-Ladung erkannt'}
              </span>
            ) : (
              <span />
            )}
            {data.length > 0 && (
              <span className="font-semibold whitespace-nowrap">
                {totalLabel}:{' '}
                {total.toLocaleString('de-DE', { minimumFractionDigits: 1, maximumFractionDigits: 1 })} kWh
              </span>
            )}
          </div>
        </>
      )}
    </div>
  );
}

export default function VerbrauchCharts() {
  return (
    <AppLayout>
      <ChartCard range="24h" every="1h" title="Letzte 24 Stunden" color={COLOR_24H} selector="date24" />
      <ChartCard range="7d" every="1h" title="Woche" color={COLOR_7D} selector="date" />
      <ChartCard range="31d" every="1d" title="Letzte 31 Tage (Monat)" color={COLOR_31D} selector="month" />
      <ChartCard range="365d" every="1mo" title="Jahr (pro Monat)" color={COLOR_365D} selector="year" />
    </AppLayout>
  );
}
