"use client";

import { EpcRating, SearchData } from "@/types/epc";
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { fetchData } from "../utils";
import { useState, use } from "react";
import { PencilSquareIcon } from "@heroicons/react/24/outline";
import PlanPart from "@/app/components/plan/PlanPart";
import EditEpctargetModal from "@/app/components/property/EditEpcTargetModal";
import Link from "next/link";
import BudgetModal from "@/app/components/plan/BudgetModal";
import { formatNumber, roundToDecimalPlaces } from "@/app/utils";
import { Part } from "@/types/parts";

export default function Plan(
  props: {
    params: Promise<{ slug: string; lmkKey: string }>;
    searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
  }
) {
  const searchParams = use(props.searchParams);
  const params = use(props.params);
  const router = useRouter();

  const portfolioId = params.slug;
  const lmkKey = params.lmkKey;
  const postcode = searchParams.postcode;

  // Temp config for the demo
  const partsConfig = [
    {
      part: "Roof",
      option: "200mm insulation",
      cost: 1200,
      co2Reduction: 1.3,
      workHours: 6,
    },
    {
      part: "Walls",
      option: "Cavity wall insulation",
      cost: 450,
      co2Reduction: 0.75,
      workHours: 20,
    },
    {
      part: "Floors",
      option: "175mm insulation",
      cost: 1200,
      co2Reduction: 1.1,
      workHours: 8,
    },
    {
      part: "Window Glazing",
      option: "Double glazing",
      cost: 4000,
      co2Reduction: 0.18,
      workHours: 15,
    },
    {
      part: "Window Draughproofing",
      option: "Draughtproofing strips",
      cost: 10,
      co2Reduction: 0.05,
      workHours: 1,
    },
    {
      part: "Door Insulation",
      option: "Sealing doors",
      cost: 250,
      co2Reduction: 0.3,
      workHours: 7,
    },
    {
      part: "Door Draughproofing",
      option: "Draughtproofing strips",
      cost: 70,
      co2Reduction: 0.1,
      workHours: 2,
    },
    {
      part: "Heating",
      option: "A efficiency boiler",
      cost: 1900,
      co2Reduction: 0.25,
      workHours: 15,
    },
    {
      part: "Hot Water",
      option: "Heat pump water heater",
      cost: 5290,
      co2Reduction: 0.15,
      workHours: 12,
    },
    {
      part: "Solar Panels",
      option: "4 roof solar panels",
      cost: 5900,
      co2Reduction: 0.08,
      workHours: 24,
    },
    {
      part: "Solar Hot Water",
      option: "Solar hot water system",
      cost: 3000,
      co2Reduction: 0.2,
      workHours: 10,
    },
    {
      part: "Lighting",
      option: "Replace bulbs with LEDs",
      cost: 20,
      co2Reduction: 0.01,
      workHours: 1,
    },
    {
      part: "Chimneys/ Open Fire Places",
      option: "Fill open fire place",
      cost: 350,
      co2Reduction: 0.15,
      workHours: 6,
    },
  ];

  const demo_ids = [
    "d290f1ee-6c54-4b01-90e6-d701748f0851",
    "d290f1ee-6c54-4b01-90e6-d701748f0852",
    "d290f1ee-6c54-4b01-90e6-d701748f0853",
    "d290f1ee-6c54-4b01-90e6-d701748f0854",
    "d290f1ee-6c54-4b01-90e6-d701748f0855",
    "d290f1ee-6c54-4b01-90e6-d701748f0856",
    "d290f1ee-6c54-4b01-90e6-d701748f0857",
    "d290f1ee-6c54-4b01-90e6-d701748f0858",
    "d290f1ee-6c54-4b01-90e6-d701748f0859",
    "d290f1ee-6c54-4b01-90e6-d701748f0860",
  ];

  // Manage state of the selected parts - start with partsConfig
  const [parts, setParts] = useState<Part[]>(partsConfig);

  const [budget, setBudget] = useState<number | "Not set">("Not set");
  const [totalCost, setTotalCost] = useState<number>(
    parts.reduce((sum, part) => sum + part.cost, 0)
  );
  const [workHours, setWorkHours] = useState(
    parts.reduce((sum, part) => sum + part.workHours, 0)
  );
  const [co2Reduction, setCo2Reduction] = useState(
    roundToDecimalPlaces(
      parts.reduce((sum, part) => sum + part.co2Reduction, 0),
      2
    )
  );

  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isBudgetModalOpen, setIsBudgetModalOpen] = useState(false);
  const [targetEpcRating, setTargetEpcRating] = useState<EpcRating | "">(
    (searchParams.targetEpcRating as EpcRating) ?? "C"
  );

  if (postcode === undefined) {
    router.push(`/portfolio/${portfolioId}/error`);
  }

  // For the demo, we want to disable this query if the portfolioId is in the demo_ids array
  const {
    data: dataResponse,
    error,
    isLoading,
  } = useQuery<SearchData, Error>({
    queryKey: ["search", postcode],
    queryFn: async () => fetchData(postcode as string),
    enabled: !demo_ids.includes(portfolioId),
  });

  // We'll be able to delete this after the demo
  let isLoadingCheck;
  let errorCheck;
  let data: SearchData;
  if (demo_ids.includes(portfolioId)) {
    // For the demo, if the demo_ids include the portfolio id we're looking at, we don't pull the property data
    // we use a pre-canned config
    isLoadingCheck = false;
    errorCheck = null;
    data = {
      "columns-names": [],
      rows: [
        {
          "low-energy-fixed-light-count": "0",
          address: "demo address",
          "uprn-source": "demo",
          "floor-height": "demo",
          "heating-cost-potential": "demo",
          "unheated-corridor-length": "demo",
          "hot-water-cost-potential": "demo",
          "construction-age-band": "demo",
          "potential-energy-rating": "demo",
          "mainheat-energy-eff": "demo",
          "windows-env-eff": "demo",
          "lighting-energy-eff": "demo",
          "environment-impact-potential": "demo",
          "glazed-type": "demo",
          "heating-cost-current": "demo",
          address3: "demo",
          "mainheatcont-description": "demo",
          "sheating-energy-eff": "demo",
          "property-type": "Flat",
          "local-authority-label": "demo",
          "fixed-lighting-outlets-count": "demo",
          "energy-tariff": "demo",
          "mechanical-ventilation": "demo",
          "hot-water-cost-current": "demo",
          county: "demo",
          postcode: "demo",
          "solar-water-heating-flag": "demo",
          constituency: "demo",
          "co2-emissions-potential": "demo",
          "number-heated-rooms": "demo",
          "floor-description": "demo",
          "energy-consumption-potential": "demo",
          "local-authority": "demo",
          "built-form": "demo",
          "number-open-fireplaces": "demo",
          "windows-description": "demo",
          "glazed-area": "demo",
          "inspection-date": "demo",
          "mains-gas-flag": "demo",
          "co2-emiss-curr-per-floor-area": "demo",
          address1: "demo",
          "heat-loss-corridor": "demo",
          "flat-storey-count": "demo",
          "constituency-label": "demo",
          "roof-energy-eff": "demo",
          "total-floor-area": "demo",
          "building-reference-number": "demo",
          "environment-impact-current": "demo",
          "co2-emissions-current": "demo",
          "roof-description": "demo",
          "floor-energy-eff": "demo",
          "number-habitable-rooms": "demo",
          address2: "demo",
          "hot-water-env-eff": "demo",
          posttown: "demo",
          "mainheatc-energy-eff": "demo",
          "main-fuel": "demo",
          "lighting-env-eff": "demo",
          "windows-energy-eff": "demo",
          "floor-env-eff": "demo",
          "sheating-env-eff": "demo",
          "lighting-description": "demo",
          "roof-env-eff": "demo",
          "walls-energy-eff": "demo",
          "photo-supply": "demo",
          "lighting-cost-potential": "demo",
          "mainheat-env-eff": "demo",
          "multi-glaze-proportion": "demo",
          "main-heating-controls": "demo",
          "lodgement-datetime": "demo",
          "flat-top-storey": "demo",
          "current-energy-rating": "D",
          "secondheat-description": "demo",
          "walls-env-eff": "demo",
          "transaction-type": "demo",
          uprn: "demo",
          "current-energy-efficiency": "demo",
          "energy-consumption-current": "demo",
          "mainheat-description": "demo",
          "lighting-cost-current": "demo",
          "lodgement-date": "demo",
          "extension-count": "demo",
          "mainheatc-env-eff": "demo",
          "lmk-key": lmkKey,
          "wind-turbine-count": "demo",
          tenure: "demo",
          "floor-level": "demo",
          "potential-energy-efficiency": "demo",
          "hot-water-energy-eff": "demo",
          "low-energy-lighting": "demo",
          "walls-description": "demo",
          "hotwater-description": "demo",
        },
      ],
    };
  } else {
    isLoadingCheck = isLoading;
    errorCheck = error;
    data = dataResponse as SearchData;
  }

  // TODO: Add a loading state and error handling
  if (isLoadingCheck) {
    return <div>Loading...</div>;
  }

  if (errorCheck) {
    return <div>Error fetching data: {errorCheck.message}</div>;
  }

  const propertyData = data.rows.filter((row) => row["lmk-key"] === lmkKey)[0];

  return (
    <section>
      <div className="max-w-6xl mx-auto p-6 flex flex-col items-center">
        <div className="text-center mb-4">
          <h1 className="text-2xl font-bold">Your Retrofit Plan</h1>
          <p>{propertyData.address}</p>
        </div>
        <div className="flex w-full">
          <div className="w-3/4 pr-4">
            {parts.map((part, index) => {
              return (
                <PlanPart
                  key={index}
                  partIndex={index}
                  title={part.part}
                  cost={part.cost}
                  option={part.option}
                  co2Reduction={part.co2Reduction}
                  workHours={part.workHours}
                  parts={parts}
                  setParts={setParts}
                  setTotalCost={setTotalCost}
                  setWorkHours={setWorkHours}
                  setCo2Reduction={setCo2Reduction}
                />
              );
            })}
          </div>
          <div className="w-1/4 ">
            <div className="bg-white p-4 rounded-lg shadow text-black ">
              <h2 className="text-lg font-bold mb-4">Summary</h2>
              <ul>
                <li
                  onClick={() => setIsEditModalOpen(true)}
                  className="hover:text-white px-2 mb-2 flex items-center cursor-pointer hover:bg-brandblue hover:rounded-md transition-colors duration-200"
                >
                  Target EPC: {targetEpcRating}
                  <PencilSquareIcon className="h-6 w-6 ml-2" />
                </li>
                <li
                  onClick={() => setIsBudgetModalOpen(true)}
                  className="hover:text-white px-2 mb-2 flex items-center cursor-pointer hover:bg-brandblue hover:rounded-md transition-colors duration-200"
                >
                  {budget !== "Not set"
                    ? "Budget: £" + formatNumber(budget)
                    : "Budget: " + budget}
                  <PencilSquareIcon className="h-6 w-6 ml-2" />
                </li>
                <Link
                  href={`/portfolio/${portfolioId}/property/${lmkKey}?postcode=${postcode}`}
                >
                  <li className="hover:text-white px-2 mb-2 flex items-center cursor-pointer hover:bg-brandblue hover:rounded-md transition-colors duration-200">
                    Edit Property Details
                    <PencilSquareIcon className="h-6 w-6 ml-2" />
                  </li>
                </Link>
                <li className="px-2 mb-2">
                  Total cost: £{formatNumber(totalCost)}
                </li>
                <li className="px-2 mb-2">
                  Installation Time: {roundToDecimalPlaces(workHours, 0)} hours
                </li>
                <li className="px-2 mb-2">
                  Co2 saved: {roundToDecimalPlaces(co2Reduction, 2)}t
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <EditEpctargetModal
        isEditModalOpen={isEditModalOpen}
        setIsEditModalOpen={setIsEditModalOpen}
        setTargetEpcRating={setTargetEpcRating}
        targetEpcRating={targetEpcRating}
        currentEpcRating={propertyData["current-energy-rating"]}
      />
      <BudgetModal
        isOpen={isBudgetModalOpen}
        setIsOpen={setIsBudgetModalOpen}
        budget={budget}
        setBudget={setBudget}
      />
    </section>
  );
}
