"use client";
import { useState } from "react";
import { formatNumber } from "@/app/utils";

interface SummaryBoxProps {
  scenarios: Array<{
    id: bigint;
    name: string;
    budget: number | null;
    totalCost: number | null;
    funding: number | null;
    contingency: number | null;
    co2EquivalentSavings: number | null;
    propertyValuationIncrease: number | null;
    energySavings: number | null;
    energyCostSavings: number | null;
    labourDays: number | null;
    isDefault: boolean;
  }>;
  numProperties: number;
}

function SummaryBox({ scenarios, numProperties }: SummaryBoxProps) {
  // Get the default scenario
  const defaultScenario =
    scenarios.find((scenario) => scenario.isDefault) || scenarios[0];

  const [selectedScenarioId, setSelectedScenarioId] = useState(
    Number(defaultScenario.id)
  );

  const [budgetFormatted, setBudgetFormatted] = useState(
    formatBudget(defaultScenario.budget)
  );
  const [totalCostFormatted, setTotalCostFormatted] = useState(
    formatMoney(defaultScenario.totalCost)
  );
  const [funding, setFunding] = useState(formatMoney(defaultScenario.funding));
  const [netCost, setNetCost] = useState(
    formatMoney(
      (defaultScenario.totalCost || 0) - (defaultScenario.funding || 0)
    )
  );
  const [contingency, setContingency] = useState(
    formatMoney(defaultScenario.contingency)
  );
  const [totalValueIncreaseFormatted, setTotalValueIncreaseFormatted] =
    useState(formatMoney(defaultScenario.propertyValuationIncrease));
  const [energyCostSavingsFormatted, setEnergyCostSavingsFormatted] = useState(
    formatMoney(defaultScenario.energyCostSavings)
  );
  const [co2EquivalentSavingsFormatted, setCo2EquivalentSavingsFormatted] =
    useState(formatCo2(defaultScenario.co2EquivalentSavings));
  const [energySavingsFormatted, setEnergySavingsFormatted] = useState(
    formatKwh(defaultScenario.energySavings)
  );

  const handleScenarioChange = (scenarioId: string) => {
    setSelectedScenarioId(Number(scenarioId));
    const selectedScenario = scenarios.find(
      (scenario) => Number(scenario.id) === Number(scenarioId)
    );

    if (!selectedScenario) {
      return;
    }

    setBudgetFormatted(formatBudget(selectedScenario.budget));
    setTotalCostFormatted(formatMoney(selectedScenario.totalCost));
    setFunding(formatMoney(selectedScenario.funding));
    setNetCost(
      formatMoney(
        (selectedScenario.totalCost || 0) - (selectedScenario.funding || 0)
      )
    );
    setContingency(formatMoney(selectedScenario.contingency));
    setTotalValueIncreaseFormatted(
      formatMoney(selectedScenario.propertyValuationIncrease)
    );
    setEnergyCostSavingsFormatted(
      formatMoney(selectedScenario.energyCostSavings)
    );
    setCo2EquivalentSavingsFormatted(
      formatCo2(selectedScenario.co2EquivalentSavings)
    );
    setEnergySavingsFormatted(formatKwh(selectedScenario.energySavings));
  };

  function formatMoney(amount: number | null) {
    if (amount === 0) {
      return "-";
    }

    return amount === null ? "-" : "£" + formatNumber(amount);
  }

  function formatBudget(budget: number | null) {
    return budget === null ? "Not set" : formatMoney(budget);
  }

  function formatHours(hours: number | null) {
    return hours === null ? "0 hours" : Math.round(hours) + " hours";
  }

  function formatCo2(co2: number | null) {
    return co2 === null ? "-" : co2.toFixed(1) + " tonnes";
  }

  function formatKwh(energy: number | null) {
    return energy === null ? "-" : formatNumber(energy) + " kWh";
  }

  return (
    <div className="p-6 bg-white rounded-lg leading-relaxed">
      <h2 className="text-2xl font-bold mb-4 text-brandblue text-center ">
        Portfolio Summary
      </h2>
      <div className="mb-4 flex items-center justify-center">
        <select
          id="scenario-select"
          value={selectedScenarioId}
          onChange={(e) => handleScenarioChange(e.target.value)}
          className="p-2 border rounded w-full text-black"
        >
          {scenarios.map((scenario) => (
            <option key={String(scenario.id)} value={String(scenario.id)}>
              {scenario.name}
            </option>
          ))}
        </select>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-1 gap-6">
        <div className="p-4 bg-gray-50 rounded-lg">
          <h3 className="text-lg font-semibold text-brandblue mb-2">
            Work Package
          </h3>
          <table className="w-full">
            <tbody>
              <tr>
                <td className="text-brandblue">Budget</td>
                <td className="text-brandblue text-end">{budgetFormatted}</td>
              </tr>
              <tr>
                <td className="text-brandblue">Cost</td>
                <td className="text-brandblue text-end">
                  {totalCostFormatted}
                </td>
              </tr>
              <tr>
                <td className="text-brandblue">Funding</td>
                <td className="text-brandblue text-end">{funding}</td>
              </tr>
              <tr>
                <td className="text-brandblue ">Cost after funding</td>
                <td className="text-brandblue text-end">{netCost}</td>
              </tr>
              <tr>
                <td className="text-brandblue">Contingency</td>
                <td className="text-brandblue text-end">{contingency}</td>
              </tr>
              <tr>
                <td className="text-brandblue">Total properties</td>
                <td className="text-brandblue text-end">{numProperties}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div className="p-4 bg-gray-50 rounded-lg">
          <h3 className="text-lg font-semibold text-brandblue mb-2">
            Environmental Impact
          </h3>
          <table className="w-full">
            <tbody>
              <tr>
                <td className="text-brandblue">
                  Annual{" "}
                  <span>
                    CO<sub>2</sub>
                  </span>{" "}
                  Savings
                </td>
                <td className="text-brandblue text-end">
                  {co2EquivalentSavingsFormatted}
                </td>
              </tr>
              <tr>
                <td className="text-brandblue">Annual Energy Savings</td>
                <td className="text-brandblue text-end">
                  {energySavingsFormatted}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div className="p-4 bg-gray-50 rounded-lg">
          <h3 className="text-lg font-semibold text-brandblue mb-2">
            Bills and Property Valuation
          </h3>
          <table className="w-full">
            <tbody>
              <tr>
                <td className="text-brandblue">Annual Energy Bill Reduction</td>
                <td className="text-brandblue text-end">
                  {energyCostSavingsFormatted}
                </td>
              </tr>
              <tr>
                <td className="text-brandblue">Total Value Increase</td>
                <td className="text-brandblue text-end">
                  {totalValueIncreaseFormatted}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default SummaryBox;
