"use client";

import { useState, useMemo } from "react";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/app/shadcn_components/ui/card";
import { BarChart } from "@tremor/react";
import type { CustomTooltipProps } from "@tremor/react";

import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/app/shadcn_components/ui/select";

import type { EpcBandCount, AgeBandCount, PropertyTypeCount } from "./types";

const friendlyKeys = {
  actual: "Actual EPCs",
  estimated: "Estimated EPCs",
  scenario: "Scenario result",
};

export function BreakdownChart({
  epcBands,
  ageBands,
  propertyTypes,
  scenarioEpcBands,
}: {
  epcBands: EpcBandCount[];
  ageBands: AgeBandCount[];
  propertyTypes: PropertyTypeCount[];
  scenarioEpcBands?: Record<string, number>;
}) {
  const [selected, setSelected] = useState("epc");

  const chartData = useMemo(() => {
    if (selected !== "epc") {
      return selected === "age"
        ? ageBands.map((d) => ({ label: d.age_band, Count: d.count }))
        : propertyTypes.map((d) => ({
            label: d.type ?? "Unknown",
            Count: d.count,
          }));
    }

    const rows: any[] = [];

    for (const d of epcBands) {
      const epc = d.epc ?? "Unknown";
      const scenarioValue = scenarioEpcBands?.[epc] ?? 0;

      // Baseline (stacked)
      rows.push({
        label: `${epc}`,
        [friendlyKeys.actual]: d.actual ?? 0,
        [friendlyKeys.estimated]: d.estimated ?? 0,
        [friendlyKeys.scenario]: 0,
      });

      // Scenario (single bar)
      rows.push({
        label: `${epc} (scenario)`,
        [friendlyKeys.actual]: 0,
        [friendlyKeys.estimated]: 0,
        [friendlyKeys.scenario]: scenarioValue,
      });
    }

    return rows;
  }, [selected, epcBands, ageBands, propertyTypes, scenarioEpcBands]);

  const categories =
    selected === "epc"
      ? [friendlyKeys.actual, friendlyKeys.estimated, friendlyKeys.scenario]
      : ["Count"];

  const colors =
    selected === "epc" ? ["#14163d", "#3943b7", "emerald"] : ["#2d348f"];

  return (
    <Card className="border border-gray-100 bg-white">
      <CardHeader className="flex flex-col space-y-1 items-start">
        <div className="flex w-full justify-between items-center">
          <CardTitle className="text-md text-brandblue">
            Property Breakdown
          </CardTitle>

          <Select value={selected} onValueChange={setSelected}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="epc">EPC Band</SelectItem>
              <SelectItem value="age">Age Band</SelectItem>
              <SelectItem value="type">Property Type</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </CardHeader>

      <CardContent>
        <BarChart
          data={chartData}
          index="label"
          categories={categories}
          colors={colors}
          valueFormatter={(v) => v.toString()}
          stack={selected === "epc"}
          customTooltip={MyTooltip}
          className="h-64"
          showGridLines={false}
        />
      </CardContent>
    </Card>
  );
}

function MyTooltip({ payload }: CustomTooltipProps) {
  if (!payload || payload.length === 0) return null;

  return (
    <div className="rounded-md bg-white shadow-lg border border-gray-200 px-3 py-2 text-xs text-gray-700">
      {payload.map((p) => (
        <div
          key={p.dataKey}
          className="flex justify-between gap-4 items-center"
        >
          <span>{p.dataKey}:</span>
          <span className="font-medium">{p.value}</span>
        </div>
      ))}
    </div>
  );
}
