import { Leaf } from "lucide-react";
import { PageHeader, Panel } from "@/components/shared/page";
import type {
  SessionEnergyReport,
  SessionTopChargepointsReport,
  SessionTopLocationsReport,
} from "@/features/analytics/session-analytics-contract";
import { TopChargepointsPanel } from "./top-chargepoints-panel";
import { TopLocationsPanel } from "./top-locations-panel";
import { estimateNetCarbonAvoided } from "./carbon-estimation";

const numberFormat = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 2,
});

function formatDateRange(startDate: string, endDate: string) {
  const format = (value: string) => {
    const date = new Date(`${value}T12:00:00Z`);
    return Number.isFinite(date.valueOf())
      ? new Intl.DateTimeFormat("en-US", {
          month: "short",
          day: "numeric",
          year: "numeric",
          timeZone: "UTC",
        }).format(date)
      : value;
  };
  return `${format(startDate)} – ${format(endDate)}`;
}

export function DashboardView({
  bestChargepoints,
  bestChargepointsError,
  worstChargepoints,
  worstChargepointsError,
  bestLocations,
  bestLocationsError,
  worstLocations,
  worstLocationsError,
  energyReport,
  energyError,
  startDate,
  endDate,
  today,
}: {
  bestChargepoints: SessionTopChargepointsReport | null;
  bestChargepointsError: string | null;
  worstChargepoints: SessionTopChargepointsReport | null;
  worstChargepointsError: string | null;
  bestLocations: SessionTopLocationsReport | null;
  bestLocationsError: string | null;
  worstLocations: SessionTopLocationsReport | null;
  worstLocationsError: string | null;
  energyReport: SessionEnergyReport | null;
  energyError: string | null;
  startDate: string;
  endDate: string;
  today: string;
}) {
  const energyKwh = energyReport?.totalEnergyKwh ?? null;
  const carbonEstimate =
    energyKwh === null ? null : estimateNetCarbonAvoided(energyKwh);
  return (
    <>
      <PageHeader title="Dashboard" />
      <div className="page-grid">
        <Panel>
          <div className="rounded-xl bg-carbon-surface p-6 text-carbon">
            <div className="flex items-center gap-2">
              <Leaf className="size-6" />
              <h2 className="font-semibold">
                Estimated Carbon Emission Avoided
              </h2>
            </div>
            <p className="mt-1 text-xs opacity-70">
              {formatDateRange(startDate, endDate)}
            </p>
            <div className="mt-5">
              <p className="text-3xl font-bold">
                {carbonEstimate === null
                  ? "Unavailable"
                  : numberFormat.format(carbonEstimate.netAvoidedKg)}{" "}
                {carbonEstimate !== null && (
                  <span className="text-base font-normal">kg CO₂</span>
                )}
              </p>
              <p className="mt-2 text-xs opacity-70">
                Estimated net operational emissions avoided
              </p>
            </div>
            <div className="mt-5 grid gap-4 border-t border-current/15 pt-4 sm:grid-cols-3">
              <div>
                <p className="text-lg font-semibold">
                  {energyKwh === null
                    ? "Unavailable"
                    : `${numberFormat.format(energyKwh)} kWh`}
                </p>
                <p className="mt-1 text-xs opacity-70">Energy delivered</p>
              </div>
              <div>
                <p className="text-lg font-semibold">
                  {carbonEstimate === null
                    ? "Unavailable"
                    : `${numberFormat.format(carbonEstimate.gasolineBaselineKg)} kg CO₂`}
                </p>
                <p className="mt-1 text-xs opacity-70">
                  Gasoline emissions baseline
                </p>
              </div>
              <div>
                <p className="text-lg font-semibold">
                  {carbonEstimate === null
                    ? "Unavailable"
                    : `${numberFormat.format(carbonEstimate.chargingElectricityKg)} kg CO₂`}
                </p>
                <p className="mt-1 text-xs opacity-70">
                  Charging electricity emissions
                </p>
              </div>
            </div>
            {energyError && (
              <p className="mt-4 text-xs text-destructive">{energyError}</p>
            )}
          </div>
        </Panel>
        <TopChargepointsPanel
          bestData={bestChargepoints}
          bestError={bestChargepointsError}
          worstData={worstChargepoints}
          worstError={worstChargepointsError}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
        <TopLocationsPanel
          bestData={bestLocations}
          bestError={bestLocationsError}
          worstData={worstLocations}
          worstError={worstLocationsError}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
      </div>
    </>
  );
}
