"use client";

import { useState, use } from "react";
import { PencilSquareIcon } from "@heroicons/react/24/outline";
import { SearchData, EpcRating, EpcKey } from "@/types/epc";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import EditEpcTargetModal from "../../../../components/property/EditEpcTargetModal";
import PartCard from "@/app/components/property/PartCard";
import { TanButton } from "@/app/components/Buttons";
import { fetchData } from "./utils";

const EpcDefaults: { [key in EpcRating]: EpcRating } = {
  G: "C",
  F: "C",
  E: "C",
  D: "C",
  C: "B",
  B: "A",
  A: "A",
};

type PartConfig = {
  title: string;
  descriptionData: {
    key: EpcKey;
    prefix: string;
    suffix: string;
  }[];
}[];

const partConfig: PartConfig = [
  {
    title: "General",
    descriptionData: [
      { key: "built-form", prefix: "", suffix: "" },
      { key: "property-type", prefix: "", suffix: "" },
    ],
  },
  {
    title: "Roof",
    descriptionData: [{ key: "roof-description", prefix: "", suffix: "" }],
  },
  {
    title: "Walls & Floors",
    descriptionData: [
      { key: "walls-description", prefix: "Walls: ", suffix: "" },
      { key: "floor-description", prefix: "Floors: ", suffix: "" },
    ],
  },
  {
    title: "Windows & Doors",
    descriptionData: [{ key: "windows-description", prefix: "", suffix: "" }],
  },
  {
    title: "Heating",
    descriptionData: [{ key: "mainheat-description", prefix: "", suffix: "" }],
  },
  {
    title: "Renewables",
    descriptionData: [
      { key: "photo-supply", prefix: "", suffix: "" },
      { key: "solar-water-heating-flag", prefix: "", suffix: "" },
    ],
  },
  {
    title: "Other",
    descriptionData: [
      { key: "lighting-description", prefix: "Lights: ", suffix: "" },
      { key: "number-open-fireplaces", prefix: "", suffix: " open fireplaces" },
      { key: "energy-tariff", prefix: "Energy tariff: ", suffix: "" },
    ],
  },
];

export default function PropertyPage(
  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;

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

  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [targetEpcRating, setTargetEpcRating] = useState<EpcRating | "">("");

  const { data, error, isLoading } = useQuery<SearchData, Error>({
    queryKey: ["search", postcode],
    queryFn: async () => fetchData(postcode as string),
  });

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

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

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

  if (targetEpcRating === "") {
    setTargetEpcRating(EpcDefaults[currentEpcRating] as EpcRating);
  }

  const handleEditClick = () => {
    setIsEditModalOpen(true);
  };

  // NextJS docs recomment fetching data directly in the component that needs it,
  // even if requeting the same data in multiple components. rather than passing data between
  // components as props

  return (
    <section>
      <div className="max-w-3xl mx-auto p-6">
        <h1 className="text-2xl text-center font-bold mb-4">Your Property</h1>

        <p className="text-center mb-4">{propertyData.address}</p>

        <div className="flex space-x-4">
          <div className="flex-1 border p-4 rounded-lg bg-brandblue text-white">
            <h2 className="text-lg font-bold mb-2">Current EPC rating</h2>
            <p>Rating: {currentEpcRating}</p>
          </div>

          <div
            className="flex-1 border p-4 rounded-lg bg-brandblue text-white hover:bg-hoverblue transition-colors duration-200 cursor-pointer"
            onClick={handleEditClick}
          >
            <h2 className="text-lg font-bold mb-2 flex">Target EPC rating</h2>
            <div className="flex">
              <p className="flex-col">Rating: {targetEpcRating}</p>
              <PencilSquareIcon className="h-6 w-6 ml-2" />
            </div>
          </div>
        </div>
        <div className="text-start mt-2">
          Review the property details below and update as required. The more you
          update, the more accurate your recommendations will be. When
          you&apos;re happy, click &quot;Build My Plan&quot; to see your
          recommended actions.
        </div>
        <div className="flex justify-center">
          <TanButton
            label="Build My Retrofit Plan"
            onClick={() => {
              router.push(
                `/portfolio/${portfolioId}/property/${lmkKey}/plan?postcode=${postcode}&targetEpcRating=${targetEpcRating}`
              );
            }}
          />
        </div>

        <div>
          {partConfig.map((part, index) => {
            const descriptionList = part.descriptionData
              .flatMap((data) => {
                const { key, prefix, suffix } = data;
                const value = propertyData[key];

                if (!value) return null;

                return `${prefix}${value}${suffix}`;
              })
              .filter((value) => value != null);

            const description = descriptionList.join(", ") || "Not present";

            return (
              <PartCard
                key={index}
                title={part.title}
                description={description}
              />
            );
          })}
        </div>

        <EditEpcTargetModal
          isEditModalOpen={isEditModalOpen}
          setIsEditModalOpen={setIsEditModalOpen}
          setTargetEpcRating={setTargetEpcRating}
          targetEpcRating={targetEpcRating}
          currentEpcRating={currentEpcRating}
        />
      </div>
    </section>
  );
}
