"use client";

import { useState } from "react";
import { RecommendationType } from "@/app/db/schema/recommendations";
import { formatNumber } from "@/app/utils";
import {
  ChevronDownIcon,
  BuildingOfficeIcon,
  HomeModernIcon,
  Square3Stack3DIcon,
  WindowIcon,
  SunIcon,
  FireIcon,
  BeakerIcon,
  ArrowPathIcon,
  AdjustmentsHorizontalIcon,
  LightBulbIcon,
  WrenchScrewdriverIcon,
  ArrowsRightLeftIcon,
} from "@heroicons/react/24/outline";
import AlternativesDrawer from "./AlternativesDrawer";
import type { AugmentedRec } from "./recommendation-types";

export type { AugmentedRec } from "./recommendation-types";

const TitleMap: Record<string, string> = {
  mechanical_ventilation: "Mechanical Ventilation",
  trickle_vents: "Trickle Vents",
  sealing_open_fireplace: "Sealing Open Fireplace",
  low_energy_lighting: "Low Energy Lighting",
  internal_wall_insulation: "Internal Wall Insulation",
  external_wall_insulation: "External Wall Insulation",
  cavity_wall_insulation: "Cavity Wall Insulation",
  extension_cavity_wall_insulation: "Extension Cavity Wall Insulation",
  loft_insulation: "Loft Insulation",
  room_roof_insulation: "Room Roof Insulation",
  flat_roof_insulation: "Flat Roof Insulation",
  sloping_ceiling_insulation: "Sloping Ceiling Insulation",
  solid_floor_insulation: "Solid Floor Insulation",
  suspended_floor_insulation: "Suspended Floor Insulation",
  exposed_floor_insulation: "Exposed Floor Insulation",
  windows_glazing: "Window Glazing",
  mixed_glazing: "Mixed Glazing",
  solar_pv: "Solar Photovoltaic Panels",
  heating: "Heating System",
  heating_control: "Heating Controls",
  secondary_heating: "Secondary Heating",
  hot_water_tank_insulation: "Hot Water Tank Insulation",
  wall_insulation: "Wall Insulation",
  floor_insulation: "Floor Insulation",
  roof_insulation: "Roof Insulation",
  cylinder_thermostat: "Cylinder Thermostat",
  draught_proofing: "Draught Proofing",
};

// All categories use a consistent cool blue accent
function getCategoryAccentColor(_category: string): string {
  return "#2563eb";
}

function CategoryIcon({ category, color }: { category: string; color: string }) {
  const cls = "w-6 h-6";
  const style = { color };
  switch (category) {
    case "wall_insulation":
    case "internal_wall_insulation":
    case "external_wall_insulation":
    case "cavity_wall_insulation":
    case "extension_cavity_wall_insulation":
      return <BuildingOfficeIcon className={cls} style={style} />;
    case "roof_insulation":
    case "loft_insulation":
    case "room_roof_insulation":
    case "flat_roof_insulation":
    case "sloping_ceiling_insulation":
      return <HomeModernIcon className={cls} style={style} />;
    case "floor_insulation":
    case "suspended_floor_insulation":
    case "solid_floor_insulation":
    case "exposed_floor_insulation":
      return <Square3Stack3DIcon className={cls} style={style} />;
    case "windows_glazing":
    case "mixed_glazing":
      return <WindowIcon className={cls} style={style} />;
    case "solar_pv":
      return <SunIcon className={cls} style={style} />;
    case "heating":
    case "secondary_heating":
    case "sealing_open_fireplace":
      return <FireIcon className={cls} style={style} />;
    case "hot_water_tank_insulation":
      return <BeakerIcon className={cls} style={style} />;
    case "mechanical_ventilation":
    case "trickle_vents":
      return <ArrowPathIcon className={cls} style={style} />;
    case "heating_control":
    case "cylinder_thermostat":
      return <AdjustmentsHorizontalIcon className={cls} style={style} />;
    case "low_energy_lighting":
      return <LightBulbIcon className={cls} style={style} />;
    default:
      return <WrenchScrewdriverIcon className={cls} style={style} />;
  }
}

type Props = {
  category: RecommendationType;
  recs: AugmentedRec[];
  selected: AugmentedRec | null;
  pendingSelection: AugmentedRec | null;
  hasPendingChange: boolean;
  isIncluded: boolean;
  isPending: boolean;
  onSelect: (rec: AugmentedRec) => void;
  onRemove: () => void;
};

export default function RecommendationCard({
  category,
  recs,
  selected,
  pendingSelection,
  hasPendingChange,
  isIncluded,
  isPending,
  onSelect,
  onRemove,
}: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);

  const alreadyInstalled = recs.some((r) => r.alreadyInstalled);
  const title = TitleMap[category] ?? category.replace(/_/g, " ");
  const isInteractive = !alreadyInstalled;

  const accentColor = getCategoryAccentColor(category);

  // Display pending selection in header chips if there's a pending change
  const displayRec = hasPendingChange ? pendingSelection : selected;

  // Display pending selection in the expanded grid too
  const displaySelected = hasPendingChange ? pendingSelection : selected;

  const alternatives = recs.filter(
    (r) => !r.alreadyInstalled && r.id !== displaySelected?.id,
  );
  const hasMore = recs.filter((r) => !r.alreadyInstalled).length > 3;

  return (
    <div
      className={`rounded-xl overflow-hidden bg-white shadow-[0_8px_30px_rgb(0,0,0,0.06)] hover:shadow-[0_12px_40px_rgb(0,0,0,0.10)] transition-all border ${
        hasPendingChange ? "border-amber-300" : "border-gray-100"
      } ${!isIncluded && !alreadyInstalled ? "opacity-60" : ""}`}
    >
      <div className="p-8">
        {/* ── Card header ─────────────────────────────────────────── */}
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-6">

          {/* Left: circular icon + title block */}
          <div className="flex items-center gap-5 flex-1 min-w-0">
            {/* Circular icon */}
            <div
              className={`w-14 h-14 rounded-full flex items-center justify-center shrink-0 ${alreadyInstalled ? "bg-amber-50" : ""}`}
              style={
                !alreadyInstalled
                  ? { backgroundColor: `${accentColor}18` }
                  : undefined
              }
            >
              {alreadyInstalled ? (
                <CategoryIcon category={category} color="#d97706" />
              ) : (
                <CategoryIcon category={category} color={accentColor} />
              )}
            </div>

            <div className="min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h4 className="text-xl font-bold font-manrope text-brandblue leading-snug">
                  {title}
                </h4>
                {!isIncluded && !alreadyInstalled && (
                  <span className="text-[10px] px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-bold uppercase tracking-wide">
                    Not included
                  </span>
                )}
              </div>
              {displayRec && !alreadyInstalled && (
                <p className="text-sm text-gray-500 font-semibold mt-0.5 truncate">
                  {displayRec.description}
                </p>
              )}
              {!displayRec && !alreadyInstalled && (
                <p className="text-sm text-gray-400 mt-0.5">
                  No measure selected
                </p>
              )}
              {alreadyInstalled && (
                <span className="mt-1 inline-block px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-700">
                  Already Installed
                </span>
              )}
            </div>
          </div>

          {/* Right: stat chips + status indicators */}
          <div className="flex items-center gap-3 shrink-0 flex-wrap justify-end">
            {hasPendingChange && !isPending && (
              <span className="text-[10px] font-bold text-amber-600 flex items-center gap-1">
                <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse inline-block" />
                Pending
              </span>
            )}
            {isPending && (
              <span className="text-xs font-bold text-gray-400 flex items-center gap-1">
                <ArrowPathIcon className="w-4 h-4 animate-spin" />
                Saving…
              </span>
            )}
            {displayRec?.sapPoints != null && displayRec.sapPoints > 0 && (
              <div className="px-3 py-2 bg-gray-50 rounded-lg text-center border border-gray-100 min-w-[72px]">
                <p className="text-[9px] font-bold uppercase tracking-widest mb-0.5 text-brandmidblue">
                  SAP Boost
                </p>
                <p className="text-sm font-black text-brandblue font-manrope">
                  +{displayRec.sapPoints.toFixed(1)}
                </p>
              </div>
            )}
            {displayRec?.energyCostSavings != null &&
              displayRec.energyCostSavings > 0 && (
                <div className="px-3 py-2 bg-gray-50 rounded-lg text-center border border-gray-100 min-w-[72px]">
                  <p className="text-[9px] font-bold text-brandmidblue uppercase tracking-widest mb-0.5">
                    Savings
                  </p>
                  <p className="text-sm font-black text-brandblue font-manrope">
                    £{formatNumber(displayRec.energyCostSavings)}/yr
                  </p>
                </div>
              )}
            {displayRec?.estimatedCost != null && displayRec.estimatedCost > 0 && (
              <div className="px-3 py-2 bg-gray-50 rounded-lg text-center border border-gray-100 min-w-[72px]">
                <p className="text-[9px] font-bold text-brandmidblue uppercase tracking-widest mb-0.5">
                  Cost
                </p>
                <p className="text-sm font-black text-brandblue font-manrope">
                  £{formatNumber(displayRec.estimatedCost)}
                </p>
              </div>
            )}
          </div>
        </div>

        {/* ── Collapsed CTA ───────────────────────────────────────── */}
        {isInteractive && !isOpen && (
          <button
            onClick={() => setIsOpen(true)}
            className="w-full py-3 rounded-xl bg-gray-50 border border-gray-100 text-brandblue font-bold text-sm hover:bg-gray-100 transition-colors flex items-center justify-center gap-2"
          >
            <ArrowsRightLeftIcon className="w-4 h-4" style={{ color: accentColor }} />
            {isIncluded
              ? "View alternative options considered"
              : "Add to plan / view options"}
          </button>
        )}

        {/* ── Expanded alternatives panel ─────────────────────────── */}
        {isInteractive && isOpen && (
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <span className="text-[10px] font-black uppercase tracking-widest text-gray-400 whitespace-nowrap">
                Detailed Alternatives
              </span>
              <div className="h-px flex-grow bg-gray-100" />
            </div>

            {/* Grid: chosen card + up to 2 alternatives */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {displaySelected && (
                <div
                  className="p-5 rounded-xl"
                  style={{
                    border: `1px solid ${accentColor}30`,
                    backgroundColor: `${accentColor}08`,
                  }}
                >
                  <div className="flex justify-between items-start mb-3">
                    <p className="font-bold text-sm text-brandblue leading-tight flex-1 mr-2">
                      {displaySelected.description}
                    </p>
                    <span
                      className="text-[10px] px-2 py-0.5 rounded font-bold uppercase whitespace-nowrap shrink-0 text-white"
                      style={{ backgroundColor: accentColor }}
                    >
                      {hasPendingChange ? "Pending" : "Chosen"}
                    </span>
                  </div>
                  {(displaySelected.sapPoints != null && displaySelected.sapPoints > 0) ||
                   (displaySelected.energyCostSavings != null && displaySelected.energyCostSavings > 0) ? (
                    <div className="flex flex-wrap gap-1.5 mb-3">
                      {displaySelected.sapPoints != null && displaySelected.sapPoints > 0 && (
                        <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-green-100 text-green-700">
                          +{displaySelected.sapPoints.toFixed(1)} SAP
                        </span>
                      )}
                      {displaySelected.energyCostSavings != null && displaySelected.energyCostSavings > 0 && (
                        <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-amber-100 text-amber-700">
                          £{formatNumber(displaySelected.energyCostSavings)}/yr saved
                        </span>
                      )}
                    </div>
                  ) : null}
                  <p className="font-black text-sm text-brandblue">
                    £{formatNumber(displaySelected.estimatedCost ?? 0)}
                  </p>
                </div>
              )}

              {alternatives.slice(0, displaySelected ? 2 : 3).map((alt) => (
                <div
                  key={String(alt.id)}
                  className="p-5 rounded-xl border border-gray-100 bg-gray-50/50 flex flex-col justify-between"
                >
                  <div>
                    <p className="font-bold text-sm text-brandblue leading-tight mb-3">
                      {alt.description}
                    </p>
                    {(alt.sapPoints != null && alt.sapPoints > 0) ||
                     (alt.energyCostSavings != null && alt.energyCostSavings > 0) ? (
                      <div className="flex flex-wrap gap-1.5 mb-3">
                        {alt.sapPoints != null && alt.sapPoints > 0 && (
                          <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-green-100 text-green-700">
                            +{alt.sapPoints.toFixed(1)} SAP
                          </span>
                        )}
                        {alt.energyCostSavings != null && alt.energyCostSavings > 0 && (
                          <span className="text-xs font-bold px-2.5 py-1 rounded-full bg-amber-100 text-amber-700">
                            £{formatNumber(alt.energyCostSavings)}/yr saved
                          </span>
                        )}
                      </div>
                    ) : null}
                  </div>
                  <div className="flex items-center justify-between mt-2">
                    <p className="font-black text-sm text-brandblue">
                      £{formatNumber(alt.estimatedCost ?? 0)}
                    </p>
                    <button
                      disabled={isPending}
                      onClick={() => onSelect(alt)}
                      className="px-3 py-1.5 text-xs font-bold rounded-lg bg-white hover:bg-gray-50 transition-colors disabled:opacity-40 border border-gray-200"
                      style={{ color: accentColor }}
                    >
                      Select
                    </button>
                  </div>
                </div>
              ))}
            </div>

            {hasMore && (
              <button
                onClick={() => setIsDrawerOpen(true)}
                className="w-full py-3 rounded-xl bg-gray-50 text-brandblue font-bold text-xs uppercase tracking-widest hover:bg-gray-100 transition-colors border border-gray-100"
              >
                Compare all {recs.filter((r) => !r.alreadyInstalled).length}{" "}
                options →
              </button>
            )}

            {/* Footer actions */}
            <div className="flex flex-col gap-2 pt-1">
              {(selected || pendingSelection) && (
                <button
                  disabled={isPending}
                  onClick={onRemove}
                  className="w-full py-3 rounded-xl border border-red-100 text-red-500 font-bold text-xs uppercase tracking-widest hover:bg-red-50 transition-colors disabled:opacity-40"
                >
                  Remove this measure from plan
                </button>
              )}
              <button
                onClick={() => setIsOpen(false)}
                className="w-full py-3 rounded-xl bg-gray-50 text-gray-500 font-bold text-xs uppercase tracking-widest hover:bg-gray-100 transition-colors flex items-center justify-center gap-2"
              >
                <ChevronDownIcon className="w-4 h-4 rotate-180" />
                Collapse alternative options
              </button>
            </div>
          </div>
        )}
      </div>

      <AlternativesDrawer
        isOpen={isDrawerOpen}
        onClose={() => setIsDrawerOpen(false)}
        categoryLabel={title}
        recs={recs}
        selected={selected}
        displaySelected={pendingSelection ?? selected}
        onSelect={(rec) => {
          onSelect(rec);
          setIsDrawerOpen(false);
        }}
        isPending={isPending}
      />
    </div>
  );
}
