'use client';

import { useEffect, useState } from 'react';

interface FahrkostenRow {
  ID: number;
  Kuerzel: string;
  Name: string;
  Anzahl: number;
}

const SATZ = Number(process.env.NEXT_PUBLIC_FAHRKOSTEN_SATZ ?? 15);

function defaultAb(): string {
  const d = new Date();
  return `${d.getFullYear()}-01-01`;
}

export default function Fahrkosten() {
  const [ab, setAb] = useState(defaultAb);
  const [rows, setRows] = useState<FahrkostenRow[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError('');
    fetch(`/api/fahrkosten?ab=${ab}`)
      .then((r) => { if (!r.ok) throw new Error(); return r.json(); })
      .then((d: FahrkostenRow[]) => { if (!cancelled) { setRows(d); setLoading(false); } })
      .catch(() => { if (!cancelled) { setError('Fehler beim Laden.'); setLoading(false); } });
    return () => { cancelled = true; };
  }, [ab]);

  const gesamt = rows ? rows.reduce((s, r) => s + r.Anzahl * SATZ, 0) : 0;

  const thCls = 'px-3 py-2 border border-gray-300 text-xs font-semibold bg-gray-100 text-left whitespace-nowrap text-gray-900';
  const thNarrowCls = `${thCls} w-16`;
  const tdCls = 'px-3 py-2 border border-gray-200 text-sm text-gray-900';
  const tdNarrowCls = `${tdCls} w-16`;
  const tdNumCls = 'px-3 py-2 border border-gray-200 text-sm text-right tabular-nums w-20 text-gray-900';

  const abFormatted = new Date(ab + 'T00:00:00').toLocaleDateString('de-DE', {
    day: '2-digit', month: '2-digit', year: 'numeric',
  });

  return (
    <div className="space-y-4 print:pl-[1.5cm]">
      <div className="flex items-center gap-3 print:hidden">
        <label className="text-sm font-medium text-gray-700 whitespace-nowrap">Ab Datum</label>
        <input
          type="date"
          value={ab}
          onChange={(e) => setAb(e.target.value)}
          className="px-2 py-1 border-2 border-gray-400 rounded-lg bg-white text-gray-900 text-sm focus:border-blue-500 focus:outline-none"
        />
      </div>

      {/* Druckkopf */}
      <div className="hidden print:block mb-2">
        <div className="text-lg font-bold">Sternwarte Welzheim — Fahrkostenabrechnung</div>
        <div className="text-sm text-gray-600">Führungen ab <strong>{abFormatted}</strong> · {SATZ} € pro Führung</div>
        <div className="text-xs text-gray-400 mt-0.5">Ausdruck vom {new Date().toLocaleDateString('de-DE')}</div>
      </div>

      {loading && <div className="text-gray-500 text-sm py-4">Lade...</div>}
      {error && <div className="text-red-600 text-sm py-4">{error}</div>}

      {!loading && !error && rows && (
        <>
          {rows.length === 0 ? (
            <div className="text-gray-500 text-sm py-4">Keine Führungen in diesem Zeitraum gefunden.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full border-collapse text-sm">
                <thead>
                  <tr>
                    <th className={thCls}>Name</th>
                    <th className={thNarrowCls}>Kürzel</th>
                    <th className={`${thNarrowCls} text-right`}>Führungen</th>
                    <th className={`${thCls} text-right`}>Fahrkosten</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r) => (
                    <tr key={r.ID} className="hover:bg-gray-50 print:hover:bg-transparent">
                      <td className={tdCls}>{r.Name}</td>
                      <td className={tdNarrowCls}>{r.Kuerzel}</td>
                      <td className={tdNumCls}>{r.Anzahl}</td>
                      <td className={tdNumCls}>{(r.Anzahl * SATZ).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })}</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr className="bg-gray-100 font-semibold">
                    <td className={`${tdCls} font-semibold`} colSpan={2}>Gesamt</td>
                    <td className={`${tdNumCls} font-semibold`}>{rows.reduce((s, r) => s + r.Anzahl, 0)}</td>
                    <td className={`${tdNumCls} font-semibold`}>{gesamt.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })}</td>
                  </tr>
                </tfoot>
              </table>
            </div>
          )}
        </>
      )}
    </div>
  );
}
