import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/app/shadcn_components/ui/card";

import {
  getEnergyAssessment,
  getEnergyAssessmentDocuments,
  getPropertyMeta,
} from "../utils";
import { DocumentsTable } from "./DocumentsTable";
import { getEpcColorClass } from "@/app/utils";

// Helper function to clean scenario names
function cleanScenarioName(scenarioName: string | undefined) {
  if (!scenarioName) {
    return scenarioName;
  }

  return scenarioName.startsWith("Scenario")
    ? scenarioName.replace(/^Scenario\s*/i, "").trim()
    : scenarioName;
}

type InfoCardProps = {
  title: string;
  value: number | string;
  unit: string;
};

const InfoCard: React.FC<InfoCardProps> = ({ title, value, unit }) => {
  const isEnergyRating = title === "Energy Rating";
  const bgColorClass = isEnergyRating ? getEpcColorClass(value.toString()) : ""; // Get the EPC color if it's Energy Rating

  return (
    <Card
      className={`flex-1 max-w-xs ${isEnergyRating ? bgColorClass : ""} ${
        isEnergyRating ? "text-white" : ""
      }`}
    >
      <CardHeader className="text-center">
        <CardTitle
          className={`${
            isEnergyRating ? "text-white" : "text-gray-700"
          } text-sm`}
        >
          {title}
        </CardTitle>
      </CardHeader>
      <CardContent className="text-center p-6">
        <div
          className={`flex justify-center items-baseline ${
            isEnergyRating ? "text-white" : "text-gray-800"
          }`}
        >
          <span className="text-4xl font-bold">{value}</span>
          <span className="ml-1 text-sm">{unit}</span>
        </div>
      </CardContent>
    </Card>
  );
};

export default async function EnergyAssessmentsPage(
  props: {
    params: Promise<{ slug: string; propertyId: string }>;
  }
) {
  const params = await props.params;
  const propertyMeta = await getPropertyMeta(params.propertyId);
  const ea = await getEnergyAssessment(propertyMeta.uprn);

  // ea will be an empty object {} if there is no energy assessment

  if (Object.keys(ea).length === 0) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center text-gray-500">
          <div className="text-2xl font-semibold mb-4">
            This property does not have a Domna energy assessment
          </div>
          <p className="text-lg">Please check back later for updates.</p>
        </div>
      </div>
    );
  }

  const documents = await getEnergyAssessmentDocuments(ea.id);

  const table1AllowedTypes = [
    "EPR",
    "Condition Report",
    "Evidence Report",
    "Summary Information",
    "Floor Plan",
  ];

  const scenarioAllowedTypes = ["Scenario Draft EPC", "Scenario Site Notes"];

  // Separate core documents and scenario-specific documents
  const coreDocuments = documents.filter(
    (doc) =>
      doc.scenarioId === null && table1AllowedTypes.includes(doc.documentType)
  );

  const scenarioDocuments = documents.filter(
    (doc) =>
      doc.scenarioId !== null && scenarioAllowedTypes.includes(doc.documentType)
  );

  // Extract unique scenarios from the documents
  const scenarios = Array.from(
    new Set(scenarioDocuments.map((doc) => doc.scenario?.scenarioName))
  ).filter(Boolean); // Filter out any null or undefined scenario names

  return (
    <div>
      {/* EPC Card and Summary Information */}
      <div className="flex flex-row justify-between my-8 space-x-6 w-full">
        {/* EPC Rating Card */}

        <InfoCard
          title="Energy Rating"
          value={ea.currentEnergyRating}
          unit={ea.currentEnergyEfficiency}
        />

        <InfoCard
          title="Carbon Emissions"
          value={ea.co2EmissionsCurrent}
          unit="tCO2/year"
        />

        <InfoCard
          title="Heat Demand"
          value={ea.energyConsumptionCurrent}
          unit="kWh/m²/year"
        />

        <InfoCard
          title="Est. Heating kWh"
          value={ea.spaceHeatingKwh}
          unit="kWh"
        />

        {/* Estimated Hot Water kWh */}
        <InfoCard
          title="Est. Hot Water kWh"
          value={ea.waterHeatingKwh}
          unit="kWh"
        />
      </div>

      {/* Core Survey Documents */}
      <div className="mt-6">
        <div className="flex items-center justify-between py-4 px-6 bg-brandblue text-white font-semibold text-lg rounded-md">
          Core Survey Documents
        </div>
        <div className="py-4">
          <DocumentsTable
            documents={coreDocuments}
            allowedTypes={table1AllowedTypes}
          />
        </div>
      </div>

      {/* Scenario-Specific Documents */}
      {scenarios.map((scenarioName) => {
        const scenarioDocs = scenarioDocuments.filter(
          (doc) => doc.scenario?.scenarioName === scenarioName
        );

        return (
          <div key={scenarioName} className="py-4">
            <div className="flex items-center justify-between py-4 px-6 bg-brandblue text-white font-semibold text-lg rounded-md">
              Scenario: {cleanScenarioName(scenarioName)}
            </div>
            <DocumentsTable
              documents={scenarioDocs}
              allowedTypes={scenarioAllowedTypes}
            />
          </div>
        );
      })}
    </div>
  );
}
