"use client";

import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  CardFooter,
} from "@/app/shadcn_components/ui/card";
import { motion } from "framer-motion";
import { Home, Zap, Leaf, LineChart, FileQuestionIcon } from "lucide-react";
import { formatNumber, sapToEpc } from "@/app/utils";
import type {
  AverageMetrics,
  EpcCoverageCounts,
  TotalMetrics,
  ScenarioOverlayMetrics,
  MetricKey,
} from "./types";

/* ───────────────────────────────────────────── */
/* Style maps                                   */
/* ───────────────────────────────────────────── */

const cardStyles: Record<
  MetricKey,
  { icon: React.ComponentType<any>; color: string }
> = {
  totalHomes: { icon: Home, color: "text-purple-600" },
  avgSap: { icon: LineChart, color: "text-blue-600" },
  avgCarbon: { icon: Leaf, color: "text-emerald-600" },
  avgBills: { icon: Zap, color: "text-amber-600" },
  missingEpc: { icon: FileQuestionIcon, color: "text-red-600" },
};

const epcColors: Record<string, string> = {
  A: "text-epc_a",
  B: "text-epc_b",
  C: "text-epc_c",
  D: "text-epc_d",
  E: "text-epc_e",
  F: "text-epc_f",
  G: "text-epc_g",
  Unknown: "text-gray-400",
};

/* ───────────────────────────────────────────── */
/* Helpers                                      */
/* ───────────────────────────────────────────── */

function hasOverlay(
  overlay: ScenarioOverlayMetrics | undefined,
): overlay is ScenarioOverlayMetrics {
  return overlay !== undefined;
}

function Skeleton({ className = "" }: { className?: string }) {
  return <div className={`animate-pulse rounded bg-gray-200 ${className}`} />;
}

/* ───────────────────────────────────────────── */
/* Component                                    */
/* ───────────────────────────────────────────── */

export function DashboardSummaryCards({
  total,
  totals,
  averages,
  epcCoverage,
  scenarioOverlay,
  loading = false,
}: {
  total: number;
  totals: TotalMetrics;
  averages: AverageMetrics;
  epcCoverage: EpcCoverageCounts;
  scenarioOverlay?: ScenarioOverlayMetrics | null;
  loading?: boolean;
}) {
  const missingEpcCount = epcCoverage.withoutEpc;
  const missingEpcPercent = total > 0 ? (missingEpcCount / total) * 100 : 0;

  const averageCurrentEpc = sapToEpc(averages.avg_sap || 0);

  const overlay = scenarioOverlay ?? undefined;
  const hasScenario = hasOverlay(overlay);

  function deltaLabel(baseline: number, scenario: number) {
    const diff = scenario - baseline;
    if (!isFinite(diff) || diff === 0) return null;

    const sign = diff > 0 ? "▲" : "▼";
    const color = diff > 0 ? "text-red-600" : "text-emerald-600";

    return (
      <span className={`text-sm font-medium ${color}`}>
        {sign} {Math.abs(diff).toFixed(2)}
      </span>
    );
  }

  const cards = [
    {
      key: "totalHomes",
      title: "Number of Homes",
      baseline: total,
      subtitle: "Total properties in this portfolio.",
    },
    {
      key: "avgSap",
      title: "Average EPC Rating",
      baseline: `${averageCurrentEpc} (${Math.round(averages.avg_sap ?? 0)} pts)`,
      scenario:
        overlay?.avgSap &&
        `${sapToEpc(overlay.avgSap.scenario)} (${overlay.avgSap.scenario} pts)`,
      subtitle: "Current SAP rating across all properties.",
      isEpc: true,
    },
    {
      key: "avgCarbon",
      title: "Carbon Emissions",
      baseline: formatNumber(averages.avg_carbon ?? 0),
      scenario: overlay?.avgCarbon && formatNumber(overlay.avgCarbon.scenario),
      units: "tCO₂e /home",
      baselineTotal: totals.total_carbon ?? 0,
      scenarioTotal: overlay?.avgCarbon?.scenarioTotal,
      subtitle: "Average annual CO₂ output per home.",
      delta:
        hasScenario && overlay?.avgCarbon
          ? deltaLabel(overlay.avgCarbon.baseline, overlay.avgCarbon.scenario)
          : null,
    },
    {
      key: "avgBills",
      title: "Energy Bills",
      baseline: formatNumber(averages.avg_bills ?? 0),
      scenario: overlay?.avgBills && formatNumber(overlay.avgBills.scenario),
      units: "/ home",
      baselineTotal: totals.total_bills ?? 0,
      scenarioTotal: overlay?.avgBills?.scenarioTotal,
      subtitle: "Estimated annual energy bills.",
      delta:
        hasScenario && overlay?.avgBills
          ? deltaLabel(overlay.avgBills.baseline, overlay.avgBills.scenario)
          : null,
    },
  ];

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
      {cards.map((c) => {
        const Icon = cardStyles[c.key as MetricKey].icon;
        const color = cardStyles[c.key as MetricKey].color;

        return (
          <Card
            key={c.key}
            className="h-full flex flex-col border border-gray-100 bg-gradient-to-br from-white to-brandlightblue/10 hover:shadow-lg transition-all duration-300"
          >
            {/* Header */}
            <CardHeader className="flex flex-row items-center gap-2 pb-1">
              {loading ? (
                <>
                  <Skeleton className="h-5 w-5 rounded-full" />
                  <Skeleton className="h-4 w-32" />
                </>
              ) : (
                <>
                  <motion.div whileHover={{ scale: 1.05 }}>
                    <Icon className={`h-5 w-5 ${color}`} />
                  </motion.div>
                  <CardTitle className="text-md font-medium text-gray-700">
                    {c.title}
                  </CardTitle>
                </>
              )}
            </CardHeader>

            {/* Content */}
            <CardContent className="flex flex-1 flex-col gap-2">
              <div
                className={`flex ${
                  hasScenario ? "justify-between" : "justify-start"
                } items-start`}
              >
                {/* Baseline */}
                <div className="flex flex-col">
                  <span className="text-xs text-gray-500">Baseline</span>

                  {loading ? (
                    <Skeleton className="h-8 w-28 mt-1" />
                  ) : (
                    <div className="flex items-baseline gap-2">
                      <span
                        className={
                          c.isEpc
                            ? `text-3xl font-semibold ${epcColors[averageCurrentEpc || "Unknown"]}`
                            : "text-3xl font-semibold bg-clip-text text-transparent bg-gradient-to-r from-brandblue to-midblue"
                        }
                      >
                        {c.key === "avgBills" ? `£${c.baseline}` : c.baseline}
                      </span>
                      {c.units && (
                        <span className="text-sm text-gray-500">{c.units}</span>
                      )}
                    </div>
                  )}

                  {c.baselineTotal !== undefined &&
                    (loading ? (
                      <Skeleton className="h-4 w-36 mt-1" />
                    ) : (
                      <span className="text-md text-gray-600">
                        Total:{" "}
                        {c.key === "avgBills"
                          ? `£${formatNumber(c.baselineTotal)}`
                          : `${formatNumber(c.baselineTotal)} tCO₂e`}
                      </span>
                    ))}
                </div>

                {/* Scenario */}
                {hasScenario && c.scenario && (
                  <div className="flex flex-col text-right">
                    <span className="text-xs text-gray-500">Scenario</span>

                    {loading ? (
                      <Skeleton className="h-7 w-24 mt-1 ml-auto" />
                    ) : (
                      <div className="flex items-baseline justify-end gap-2">
                        <span
                          className={
                            c.isEpc
                              ? `text-2xl font-semibold ${
                                  epcColors[
                                    sapToEpc(
                                      overlay?.avgSap?.scenario ??
                                        (averages.avg_sap || 0),
                                    ) || "Unknown"
                                  ]
                                }`
                              : "text-2xl font-semibold text-brandblue"
                          }
                        >
                          {c.key === "avgBills" ? `£${c.scenario}` : c.scenario}
                        </span>
                        {c.delta && <span>{c.delta}</span>}
                      </div>
                    )}

                    {c.scenarioTotal !== undefined &&
                      (loading ? (
                        <Skeleton className="h-4 w-36 mt-1 ml-auto" />
                      ) : (
                        <span className="text-md text-gray-600">
                          Total:{" "}
                          {c.key === "avgBills"
                            ? `£${formatNumber(c.scenarioTotal)}`
                            : `${formatNumber(c.scenarioTotal)} tCO₂e`}
                        </span>
                      ))}
                  </div>
                )}
              </div>

              {/* Missing EPC bar */}
              {c.key === "missingEpc" && (
                <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                  <div
                    className="h-2 rounded-full bg-red-500"
                    style={{ width: `${missingEpcPercent}%` }}
                  />
                </div>
              )}
            </CardContent>

            <CardFooter>
              {loading ? (
                <Skeleton className="h-3 w-3/4" />
              ) : (
                <p className="text-xs text-gray-500">{c.subtitle}</p>
              )}
            </CardFooter>
          </Card>
        );
      })}
    </div>
  );
}
