"use client";

import { Card, CardContent, CardHeader } from "@/app/shadcn_components/ui/card";
import { CheckCircle, XCircle, HelpCircle } from "lucide-react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/app/shadcn_components/ui/accordion";
import clsx from "clsx";
import { AlertTriangle } from "lucide-react";
import { PropertyDetailsEpc } from "@/app/db/schema/property";
import {
  getAllRoomData,
  getRoomsWithDamp,
  getRoomsWithDefects,
  getRoomsWithBadWindows,
  areAllWindowsOk,
  getElevationsWithIssues,
  hasSufficientSpace,
  hasEfficientHeatingSystem,
  isInsulationAdequate,
  meetsSapThreshold,
} from "./decent_homes_utils";

type Rating = 1 | 2 | 3 | 4 | 5;

const RatingMap: Record<Rating, string> = {
  1: "Very Poor",
  2: "Poor",
  3: "Average",
  4: "Good",
  5: "Very Good",
};

function ChecklistItem({
  label,
  passed,
  note,
  alert = false,
  roomsWithIssues = [],
}: {
  label: string;
  passed?: boolean;
  note?: string;
  alert?: boolean;
  roomsWithIssues?: [string, any][];
}) {
  const icon =
    passed === true ? (
      <CheckCircle className="text-brandbrown w-5 h-5 shrink-0" />
    ) : passed === false ? (
      <XCircle
        className={clsx(
          "w-5 h-5 shrink-0",
          alert ? "text-red-600" : "text-brandblue"
        )}
      />
    ) : (
      <HelpCircle className="text-brandblue w-5 h-5 shrink-0" />
    );

  return (
    <div className="bg-muted/50 px-3 py-2 rounded-md space-y-2">
      <div className="flex items-center gap-3">
        {icon}
        <span className="text-sm font-medium text-foreground">
          {label}
          {note && (
            <span className="ml-1 text-xs text-muted-foreground font-normal">
              ({note})
            </span>
          )}
        </span>
      </div>

      {roomsWithIssues.length > 0 && (
        <Accordion
          type="multiple"
          className="ml-6 border-l border-muted pl-4 mt-2"
        >
          {roomsWithIssues.map(([roomName, room]: any) => (
            <AccordionItem key={roomName} value={roomName}>
              <AccordionTrigger>{formatRoomName(roomName)}</AccordionTrigger>
              <AccordionContent>
                <div className="text-sm text-muted-foreground space-y-1 px-1">
                  {room.room_info?.overall_condition_of_the_room && (
                    <div>
                      <strong>Condition:</strong>{" "}
                      {room.room_info.overall_condition_of_the_room}
                    </div>
                  )}
                  {room.room_info?.does_the_room_have_any_defects === "Yes" && (
                    <div className="flex items-start gap-2 text-brandblue">
                      <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
                      <div>
                        <div>
                          <strong>Defect reported</strong>
                        </div>
                        {room.room_info?.description_of_defect && (
                          <div className="text-sm text-muted-foreground">
                            {room.room_info.description_of_defect}
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                  {room.room_info?.ventilation_info
                    ?.location_of_any_damp_or_mould && (
                    <div className="flex items-center gap-2 text-red-600">
                      <AlertTriangle className="w-4 h-4 shrink-0" />
                      <span>
                        <strong>Damp/Mould Location:</strong>{" "}
                        {
                          room.room_info.ventilation_info
                            .location_of_any_damp_or_mould
                        }
                        <span className="ml-2 text-xs text-muted-foreground italic">
                          (Severity: Average)
                        </span>
                      </span>
                    </div>
                  )}
                  {room.room_info?.windows_info?.condition_of_the_windows && (
                    <div>
                      <strong>Window Condition:</strong>{" "}
                      {room.room_info.windows_info.condition_of_the_windows}
                    </div>
                  )}
                </div>
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>
      )}
    </div>
  );
}

function formatRoomName(name: string) {
  return name
    .replaceAll("_", " ")
    .replace(/\b\w/g, (l) => l.toUpperCase())
    .replace("Room Info", "Room");
}

export default function ConditionReport({
  conditionReport,
  totalFloorArea,
  currentSapPoints,
  conditionData,
}: {
  conditionReport: {
    rooms: Record<string, any>;
    [key: string]: any;
  };
  totalFloorArea: number;
  currentSapPoints: number;
  conditionData: PropertyDetailsEpc;
}) {
  const allRoomData = getAllRoomData(conditionReport.rooms);
  const roomsWithDamp = getRoomsWithDamp(allRoomData);
  const roomsWithDefects = getRoomsWithDefects(allRoomData);
  const roomsWithBadWindows = getRoomsWithBadWindows(allRoomData);
  const windowsOk = areAllWindowsOk(allRoomData);

  const elevationsWithIssues = getElevationsWithIssues(
    conditionReport.access_and_elevations
  );

  const {
    isSufficient: enoughSpace,
    occupantsToUse,
    numberOfBedrooms,
    areaPerPerson,
  } = hasSufficientSpace(conditionReport, totalFloorArea, allRoomData);

  const sapOk = meetsSapThreshold(currentSapPoints);
  const efficientHeating = hasEfficientHeatingSystem(
    conditionData.heatingRating
  );
  const insulationOk = isInsulationAdequate(
    conditionData.roofRating,
    conditionData.wallsRating
  );
  const thermalComfortOk = efficientHeating && insulationOk;

  const kitchenOk =
    conditionReport.rooms.kitchen?.room_info?.overall_condition_of_the_room ===
    "Good";
  const bathroomsOk =
    Array.isArray(conditionReport.rooms.bathrooms) &&
    conditionReport.rooms.bathrooms.length > 0 &&
    conditionReport.rooms.bathrooms.every(
      (b: any) => b?.room_info?.overall_condition_of_the_room === "Good"
    );
  const hasDefects = roomsWithDefects.length > 0;

  return (
    <div className="space-y-6 mt-8">
      <Card>
        <CardHeader className="text-lg font-semibold text-brandblue">
          Decent Homes Checklist
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-3">
              <h3 className="text-sm font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
                Category 1 Hazards
              </h3>

              <ChecklistItem
                label={
                  elevationsWithIssues.length > 0
                    ? "Structural issues identified"
                    : "No major structural issues identified"
                }
                passed={elevationsWithIssues.length === 0}
                alert={elevationsWithIssues.length > 0}
                roomsWithIssues={elevationsWithIssues}
              />

              <ChecklistItem
                label={
                  roomsWithDamp.length > 0
                    ? "Signs of damp or mould present"
                    : "No signs of damp or mould"
                }
                passed={roomsWithDamp.length === 0}
                alert={roomsWithDamp.length > 0}
                roomsWithIssues={roomsWithDamp}
              />

              <ChecklistItem
                label={
                  conditionReport.heating_system?.general_condition
                    ?.is_the_heating_system_in_working_order
                    ? "Heating system operational"
                    : "Heating system not operational"
                }
                passed={
                  conditionReport.heating_system?.general_condition
                    ?.is_the_heating_system_in_working_order
                }
                alert={
                  !conditionReport.heating_system?.general_condition
                    ?.is_the_heating_system_in_working_order
                }
              />

              <ChecklistItem
                label={
                  sapOk
                    ? "SAP rating meets minimum threshold (≥ 35)"
                    : "SAP rating below recommended minimum"
                }
                passed={sapOk}
                alert={!sapOk}
                note={`SAP Points: ${currentSapPoints}`}
              />

              <ChecklistItem
                label={
                  thermalComfortOk
                    ? "Thermal comfort conditions met"
                    : "Thermal comfort conditions not met"
                }
                passed={thermalComfortOk}
                alert={!thermalComfortOk}
                note={`Heating: ${conditionData.heating}; Roof Rating: ${RatingMap[conditionData.roofRating as Rating] ?? "N/A"}; Wall Rating: ${RatingMap[conditionData.wallsRating as Rating] ?? "N/A"}`}
              />
            </div>

            <div className="space-y-3">
              <h3 className="text-sm font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
                Category 2 Hazards
              </h3>

              <ChecklistItem
                label={
                  hasDefects
                    ? "Room defects present"
                    : "No room defects present"
                }
                passed={!hasDefects}
                alert={hasDefects}
                roomsWithIssues={roomsWithDefects}
              />

              <ChecklistItem
                label={
                  windowsOk
                    ? "Windows in good condition"
                    : "Windows not in good condition"
                }
                passed={windowsOk}
                alert={!windowsOk}
                roomsWithIssues={roomsWithBadWindows}
              />

              <ChecklistItem
                label={
                  kitchenOk
                    ? "Kitchen in good condition"
                    : "Kitchen not in good condition"
                }
                passed={kitchenOk}
                alert={!kitchenOk}
              />

              <ChecklistItem
                label={
                  bathroomsOk
                    ? "Bathrooms in good condition"
                    : "Bathrooms not in good condition"
                }
                passed={bathroomsOk}
                alert={!bathroomsOk}
              />

              <ChecklistItem
                label="Sufficient space for number of occupants"
                passed={enoughSpace}
                alert={!enoughSpace}
                note={`${occupantsToUse} occupants, ${numberOfBedrooms} bedrooms. ${areaPerPerson.toFixed(1)}m² per person`}
              />
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
