import { Totals as TotalsData } from "@/lib/db";

function kwh(wh: number): string {
  return (wh / 1000).toLocaleString("de-DE", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

function formatInstall(iso: string | null): string {
  if (!iso) return "";
  const [date = ""] = iso.split("T");
  const [y, m, d] = date.split("-");
  return y && m && d ? ` (seit ${d}.${m}.${y})` : "";
}

function Card({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex-1 min-w-[10rem] border border-black rounded-lg bg-white p-4 text-center">
      <div className="text-sm text-gray-600">{label}</div>
      <div className="text-2xl font-bold">
        {value} <span className="text-base font-normal">kWh</span>
      </div>
    </div>
  );
}

export default function Totals({ totals }: { totals: TotalsData }) {
  return (
    <div className="mt-6">
      <h2 className="text-lg font-semibold mb-3">Geladene Energie</h2>
      <div className="flex flex-wrap gap-4">
        <Card label="Aktueller Monat" value={kwh(totals.month_wh)} />
        <Card label="Aktuelles Jahr" value={kwh(totals.year_wh)} />
        <Card
          label={`Gesamt${formatInstall(totals.install_date)}`}
          value={kwh(totals.total_wh)}
        />
      </div>
    </div>
  );
}
