"use client";

import type { ReactNode } from "react";
import {
  CheckCircleIcon,
  XCircleIcon,
  MinusCircleIcon,
  HomeIcon,
  WrenchScrewdriverIcon,
  SparklesIcon,
  FireIcon,
  ExclamationTriangleIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";
import {
  CheckCircleIcon as CheckCircleSolid,
  XCircleIcon as XCircleSolid,
} from "@heroicons/react/24/solid";
import { AlertTriangle, Hourglass } from "lucide-react";

// ── Constants ─────────────────────────────────────────────────────────────────

const DISPLAY_NAMES: Record<string, string> = {
  damp_and_mould_growth: "Damp and Mould Growth",
  excess_cold: "Excess Cold",
  excess_heat: "Excess Heat",
  asbestos_and_mm_fibres: "Asbestos and MM Fibres",
  biocides: "Biocides",
  carbon_monoxide: "Carbon Monoxide",
  lead: "Lead",
  radiation: "Radiation",
  uncombusted_fuel_gas: "Uncombusted Fuel Gas",
  volatile_organic_compounds: "Volatile Organic Compounds",
  crowding_and_space: "Crowding and Space",
  entry_by_intruders: "Entry by Intruders",
  lighting: "Lighting",
  noise: "Noise",
  domestic_hygiene_pests_and_refuse: "Domestic Hygiene, Pests, and Refuse",
  food_safety: "Food Safety",
  personal_hygiene_sanitation_and_drainage: "Personal Hygiene, Sanitation, and Drainage",
  water_supply: "Water Supply",
  falls_associated_with_baths: "Falls Associated with Baths",
  falls_on_level_surfaces: "Falls on Level Surfaces",
  falls_on_stairs_and_steps: "Falls on Stairs and Steps",
  falls_between_levels: "Falls Between Levels",
  electrical_hazards: "Electrical Hazards",
  fire: "Fire",
  flames_hot_surfaces_and_materials: "Flames, Hot Surfaces, and Materials",
  collision_and_entrapment: "Collision and Entrapment",
  explosions: "Explosions",
  ergonomics: "Ergonomics",
  structural_collapse_and_falling_elements: "Structural Collapse and Falling Elements",
  wall_structure: "Wall Structure",
  lintels: "Lintels",
  wall_finish: "Wall Finish",
  roof_structure: "Roof Structure",
  roof_finish: "Roof Finish",
  chimneys: "Chimneys",
  windows: "Windows",
  external_doors: "External Doors",
  heating_other: "Other Heating Systems",
  electrical_systems: "Electrical Systems",
  kitchen: "Kitchen",
  bathroom: "Bathroom",
  kitchen_less_than_20_years_old: "Kitchen Less Than 20 Years Old",
  kitchen_adequate_space_and_layout: "Kitchen Has Adequate Space and Layout",
  bathroom_less_than_30_years_old: "Bathroom Less Than 30 Years Old",
  bathroom_wc_appropriately_located: "Bathroom/WC Appropriately Located",
  adequate_external_noise_insulation: "Adequate External Noise Insulation",
  efficient_heating_system_type: "Efficient Heating System Type",
  efficient_heating_distribution: "Efficient Heating Distribution",
  loft_insulation_sufficient: "Loft Insulation Sufficient",
  wall_insulation_sufficient: "Wall Insulation Sufficient",
};

const SUB_ITEMS_TEXT: Record<string, string> = {
  "Wall Structure in External Area": "Wall Structure Renewal",
  "Lintels in External Area": "Lintel Renewal",
  "Wall Finish 1 in External Area": "Wall Finish Renewal",
  "Brickwork Pointing in External Area": "Brickwork Pointing Renewal",
  "Roof Structure 1 in External Area": "Roof Structure Renewal",
  "Fascia / Soffit / Bargeboard in External Area": "Fascia / Soffit / Bargeboard Renewal",
  "Gutters in External Area": "Gutter Renewal",
  "Downpipes in External Area": "Downpipe Renewal",
  "Roof Covering 1 in External Area": "Roof Covering Replacement",
  "Chimneys in External Area": "Chimney Renewal",
  "Windows in Property": "Window Replacement",
  "Windows 1 in External Area": "Window Replacement",
  "Type and Location of Front Door in Property": "Front Door Replacement",
  "Back and Side Doors 1 in External Area": "Door Replacement",
  "Back and Side Doors 2 in External Area": "Door Replacement",
  "Type of Water Heating in Property": "Water Heating System Replacement",
  "Electrics Required in Property": "Electrical System Renewal",
  "Adequacy of Kitchen and Type in Property": "Kitchen Renewal",
  "Adequacy of Bathroom Location in Property": "Bathroom Renewal",
  kitchen_less_than_20_years_old: "Kitchen Replacement",
  kitchen_adequate_space_and_layout: "Kitchen Layout Upgrade",
  bathroom_less_than_30_years_old: "Bathroom Replacement",
  bathroom_wc_appropriately_located: "Bathroom/WC Layout Upgrade",
  adequate_external_noise_insulation: "Noise Insulation Upgrade",
  efficient_heating_system_type: "Heating System Upgrade",
  efficient_heating_distribution: "Heating Distribution Upgrade",
  loft_insulation_sufficient: "Loft Insulation Upgrade",
  wall_insulation_sufficient: "Wall Insulation Upgrade",
};

// ── Types ─────────────────────────────────────────────────────────────────────

type MetaItem = {
  criteria: string;
  sub_variable: string;
  result: string;
  expiry_date?: string | null;
  install_date?: string | null;
};

type ReplacementEntry = {
  label: string;
  expiry: Date;
  install: Date;
  remaining: string;
  overdue: boolean;
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function getStatusIcon(status: string) {
  if (status === "pass") return <CheckCircleSolid className="w-4 h-4 text-emerald-500 shrink-0" />;
  if (status === "fail") return <XCircleSolid className="w-4 h-4 text-red-500 shrink-0" />;
  return <MinusCircleIcon className="w-4 h-4 text-gray-400 shrink-0" />;
}

function getStatusDot(status: string) {
  const colorMap: Record<string, string> = {
    pass: "bg-emerald-500",
    fail: "bg-red-500",
    no_data: "bg-gray-300",
  };
  return <span className={`w-2 h-2 rounded-full shrink-0 ${colorMap[status] ?? "bg-gray-300"}`} />;
}

function getOverallStyles(status: string): { bg: string; text: string; border: string } {
  if (status === "pass") return { bg: "bg-emerald-50", text: "text-emerald-800", border: "border-emerald-200" };
  if (status === "fail") return { bg: "bg-red-50", text: "text-red-800", border: "border-red-200" };
  return { bg: "bg-gray-50", text: "text-gray-700", border: "border-gray-200" };
}

function getOverallLabel(status: string): string {
  if (status === "pass") return "Decent Homes: Pass";
  if (status === "fail") return "Decent Homes: Fail";
  return "Information Missing";
}

function getCriterionStatusBadge(status: string) {
  if (status === "pass") {
    return (
      <span className="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-700">
        <CheckCircleSolid className="w-3 h-3" />
        Pass
      </span>
    );
  }
  if (status === "fail") {
    return (
      <span className="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full bg-red-50 border border-red-200 text-red-700">
        <XCircleSolid className="w-3 h-3" />
        Fail
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full bg-gray-50 border border-gray-200 text-gray-500">
      <MinusCircleIcon className="w-3 h-3" />
      No Data
    </span>
  );
}

function parseReplacements(items: MetaItem[]): ReplacementEntry[] {
  const today = new Date();
  return items
    .filter((r) => r.expiry_date && r.install_date)
    .map((r) => {
      const expiry = new Date(r.expiry_date!);
      const install = new Date(r.install_date!);
      const diffMs = expiry.getTime() - today.getTime();
      const diffMonths = diffMs / (1000 * 60 * 60 * 24 * 30);
      const years = Math.floor(Math.abs(diffMonths) / 12);
      const months = Math.floor(Math.abs(diffMonths) % 12);
      const overdue = diffMs < 0;
      const remaining = overdue
        ? `Expired ${years > 0 ? `${years}y ` : ""}${months}m ago`
        : `${years > 0 ? `${years}y ` : ""}${months}m remaining`;
      return {
        label: SUB_ITEMS_TEXT[r.sub_variable] ?? r.sub_variable,
        expiry,
        install,
        remaining,
        overdue,
      };
    })
    .sort((a, b) => a.expiry.getTime() - b.expiry.getTime());
}

function groupReplacements(entries: ReplacementEntry[]) {
  const groups: Record<string, ReplacementEntry[]> = {
    Overdue: [],
    "0–6 months": [],
    "6–12 months": [],
    ">12 months": [],
  };
  for (const e of entries) {
    const diffMs = e.expiry.getTime() - Date.now();
    const diffMonths = diffMs / (1000 * 60 * 60 * 24 * 30);
    if (e.overdue) groups.Overdue.push(e);
    else if (diffMonths <= 6) groups["0–6 months"].push(e);
    else if (diffMonths <= 12) groups["6–12 months"].push(e);
    else groups[">12 months"].push(e);
  }
  return groups;
}

// ── Sub-components ────────────────────────────────────────────────────────────

function CriterionCard({
  letter,
  label,
  description,
  icon,
  status,
  items,
}: {
  letter: string;
  label: string;
  description: string;
  icon: ReactNode;
  status: string;
  items: { sub_variable: string; result: string }[];
}) {
  const sorted = [...items].sort((a, b) => {
    const order = { fail: 0, no_data: 1, pass: 2 };
    return (order[a.result as keyof typeof order] ?? 1) - (order[b.result as keyof typeof order] ?? 1);
  });

  const failCount = items.filter((i) => i.result === "fail").length;
  const passCount = items.filter((i) => i.result === "pass").length;
  const notAssessedCount = items.length - passCount - failCount;

  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden flex flex-col">
      {/* Card header */}
      <div className="p-5 pb-4 flex items-start justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-xl bg-brandblue flex items-center justify-center shrink-0">
            <span className="text-white">{icon}</span>
          </div>
          <div>
            <p className="text-[10px] font-bold text-brandmidblue uppercase tracking-widest">
              Criterion {letter}
            </p>
            <p className="font-manrope font-bold text-sm text-brandblue leading-tight">{label}</p>
          </div>
        </div>
        {getCriterionStatusBadge(status)}
      </div>

      {/* Description */}
      <p className="text-xs text-gray-400 px-5 pb-3 leading-relaxed">{description}</p>

      {/* Stats row */}
      <div className="flex items-center gap-3 px-5 pb-3">
        <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-emerald-700">
          <CheckCircleSolid className="w-3 h-3" />
          {passCount} pass
        </span>
        <span className="text-gray-200">·</span>
        <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-red-600">
          <XCircleSolid className="w-3 h-3" />
          {failCount} fail
        </span>
        {notAssessedCount > 0 && (
          <>
            <span className="text-gray-200">·</span>
            <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-gray-400">
              <MinusCircleIcon className="w-3 h-3" />
              {notAssessedCount} not assessed
            </span>
          </>
        )}
      </div>

      {/* Scrollable item list */}
      <div className="relative flex-1 border-t border-gray-100">
        <div className="max-h-[320px] overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden divide-y divide-gray-100">
          {sorted.map((item, idx) => (
            <div
              key={idx}
              className="flex items-center justify-between px-5 py-2.5 hover:bg-gray-50 transition-colors"
            >
              <span className="text-xs text-gray-700 pr-3">
                {DISPLAY_NAMES[item.sub_variable] ?? item.sub_variable}
              </span>
              {getStatusIcon(item.result)}
            </div>
          ))}
        </div>
        {/* Gradient fade to indicate more items below */}
        <div className="pointer-events-none absolute bottom-0 inset-x-0 h-8 bg-gradient-to-t from-white to-transparent z-10" />
      </div>
    </div>
  );
}

function ReplacementsSection({ items }: { items: MetaItem[] }) {
  const entries = parseReplacements(items);
  const groups = groupReplacements(entries);

  const urgencyConfig: Record<string, {
    border: string;
    headerBg: string;
    badge: string;
    icon: ReactNode;
    label: string;
  }> = {
    Overdue: {
      border: "border-red-200",
      headerBg: "bg-red-50",
      badge: "bg-red-100 text-red-800 border-red-200",
      icon: <AlertTriangle className="w-3.5 h-3.5 text-red-600" />,
      label: "Overdue",
    },
    "0–6 months": {
      border: "border-orange-200",
      headerBg: "bg-orange-50",
      badge: "bg-orange-100 text-orange-800 border-orange-200",
      icon: <ClockIcon className="w-3.5 h-3.5 text-orange-600" />,
      label: "0–6 months",
    },
    "6–12 months": {
      border: "border-yellow-200",
      headerBg: "bg-yellow-50",
      badge: "bg-yellow-100 text-yellow-800 border-yellow-200",
      icon: <Hourglass className="w-3.5 h-3.5 text-yellow-600" />,
      label: "6–12 months",
    },
    ">12 months": {
      border: "border-emerald-200",
      headerBg: "bg-emerald-50",
      badge: "bg-emerald-100 text-emerald-800 border-emerald-200",
      icon: <CheckCircleIcon className="w-3.5 h-3.5 text-emerald-600" />,
      label: ">12 months",
    },
  };

  const order = ["Overdue", "0–6 months", "6–12 months", ">12 months"] as const;

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
      {order.map((urgency) => {
        const cfg = urgencyConfig[urgency];
        const list = groups[urgency];
        return (
          <div
            key={urgency}
            className={`rounded-2xl border ${cfg.border} overflow-hidden flex flex-col bg-white shadow-sm`}
          >
            {/* Column header */}
            <div className={`${cfg.headerBg} px-4 py-3 flex items-center justify-between border-b ${cfg.border} shrink-0`}>
              <div className="flex items-center gap-1.5">
                {cfg.icon}
                <span className="text-xs font-bold text-gray-700">{cfg.label}</span>
              </div>
              <span className={`text-xs font-bold px-2 py-0.5 rounded-full border ${cfg.badge}`}>
                {list.length}
              </span>
            </div>

            {/* Scrollable body */}
            <div className="relative flex-1">
              <div className="max-h-[400px] overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden divide-y divide-gray-100">
                {list.length === 0 ? (
                  <p className="text-xs text-gray-400 text-center py-6">None</p>
                ) : (
                  list.map((entry, idx) => (
                    <div key={idx} className="px-4 py-3">
                      <p className="text-xs font-semibold text-gray-800 mb-1">{entry.label}</p>
                      <p className={`text-[10px] font-medium ${entry.overdue ? "text-red-600" : "text-gray-500"}`}>
                        {entry.remaining}
                      </p>
                      <div className="flex justify-between mt-1">
                        <p className="text-[10px] text-gray-400">
                          Installed: {entry.install.toLocaleDateString("en-GB")}
                        </p>
                        <p className={`text-[10px] ${entry.overdue ? "text-red-500" : "text-gray-400"}`}>
                          Expires: {entry.expiry.toLocaleDateString("en-GB")}
                        </p>
                      </div>
                    </div>
                  ))
                )}
              </div>
              {list.length > 0 && (
                <div className="pointer-events-none absolute bottom-0 inset-x-0 h-8 bg-gradient-to-t from-white to-transparent z-10" />
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── Data ──────────────────────────────────────────────────────────────────────

const CRITERIA: {
  key: "A" | "B" | "C" | "D";
  letter: string;
  label: string;
  description: string;
  icon: ReactNode;
  statusKey: string;
}[] = [
  {
    key: "A",
    letter: "A",
    label: "Statutory Standard",
    description: "Meets current statutory minimum standard for housing",
    icon: <HomeIcon className="w-4 h-4" />,
    statusKey: "criterion_a",
  },
  {
    key: "B",
    letter: "B",
    label: "State of Repair",
    description: "The home is in a reasonable state of repair",
    icon: <WrenchScrewdriverIcon className="w-4 h-4" />,
    statusKey: "criterion_b",
  },
  {
    key: "C",
    letter: "C",
    label: "Modern Facilities",
    description: "Has reasonable modern facilities and services",
    icon: <SparklesIcon className="w-4 h-4" />,
    statusKey: "criterion_c",
  },
  {
    key: "D",
    letter: "D",
    label: "Thermal Comfort",
    description: "Provides a reasonable degree of thermal comfort",
    icon: <FireIcon className="w-4 h-4" />,
    statusKey: "criterion_d",
  },
];

// ── Main export ───────────────────────────────────────────────────────────────

export default function DecentHomesSummary({
  decentHomes,
  decentHomesMeta,
}: {
  decentHomes: {
    uprn: number;
    creation_date: string;
    criterion_a: string;
    criterion_b: string;
    criterion_c: string;
    criterion_d: string;
    decent_homes: string;
  };
  decentHomesMeta: MetaItem[];
}) {
  const criteriaGroups: Record<string, { sub_variable: string; result: string }[]> = {
    A: [], B: [], C: [], D: [],
  };
  for (const item of decentHomesMeta) {
    if (criteriaGroups[item.criteria]) {
      criteriaGroups[item.criteria].push({
        sub_variable: item.sub_variable,
        result: item.result,
      });
    }
  }

  const overdueCount = decentHomesMeta.filter((r) => {
    if (!r.expiry_date) return false;
    return new Date(r.expiry_date).getTime() < Date.now();
  }).length;

  const overallStatus = decentHomes.decent_homes;
  const overall = getOverallStyles(overallStatus);
  const overallLabel = getOverallLabel(overallStatus);

  const lastUpdated = new Date(decentHomes.creation_date).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  const criterionStatus: Record<string, string> = {
    A: decentHomes.criterion_a,
    B: decentHomes.criterion_b,
    C: decentHomes.criterion_c,
    D: decentHomes.criterion_d,
  };

  return (
    <div className="max-w-7xl mx-auto py-10 space-y-10">

      {/* ── Page header ──────────────────────────────────────────────────── */}
      <header>
        <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-2">
          Housing Standards
        </p>
        <h1 className="font-manrope font-extrabold text-4xl text-brandblue tracking-tight">
          Decent Homes Assessment
        </h1>
      </header>

      {/* ── Hero card ────────────────────────────────────────────────────── */}
      <div className={`rounded-2xl border ${overall.border} ${overall.bg} p-8 flex flex-wrap items-center justify-between gap-6`}>
        <div className="flex items-center gap-4">
          {overallStatus === "pass" ? (
            <CheckCircleSolid className="w-12 h-12 text-emerald-500 shrink-0" />
          ) : overallStatus === "fail" ? (
            <XCircleSolid className="w-12 h-12 text-red-500 shrink-0" />
          ) : (
            <ExclamationTriangleIcon className="w-12 h-12 text-gray-400 shrink-0" />
          )}
          <div>
            <p className="font-manrope font-extrabold text-2xl text-gray-900 tracking-tight">
              {overallLabel}
            </p>
            <p className="text-sm text-gray-500 mt-0.5">
              Decent Homes Standard assessment · Last updated {lastUpdated}
            </p>
          </div>
        </div>

        {/* Criteria summary pills */}
        <div className="flex gap-3 flex-wrap">
          {CRITERIA.map((c) => {
            const s = criterionStatus[c.letter];
            return (
              <div
                key={c.key}
                className="flex items-center gap-2 text-xs font-semibold text-gray-600 bg-white border border-gray-200 rounded-full px-3 py-1.5 shadow-sm"
              >
                {getStatusDot(s)}
                <span>Criterion {c.letter}</span>
                <span className="text-gray-400 font-normal">{c.label}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* ── Criteria cards ───────────────────────────────────────────────── */}
      <section>
        <div className="flex items-center gap-3 mb-6">
          <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest">
            Assessment Criteria
          </p>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {CRITERIA.map((c) => (
            <CriterionCard
              key={c.key}
              letter={c.letter}
              label={c.label}
              description={c.description}
              icon={c.icon}
              status={criterionStatus[c.letter]}
              items={criteriaGroups[c.letter]}
            />
          ))}
        </div>
      </section>

      {/* ── Replacements section ─────────────────────────────────────────── */}
      <section>
        <div className="flex items-center gap-3 mb-6">
          <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest">
            Component Replacements
          </p>
          {overdueCount > 0 && (
            <span className="bg-red-100 text-red-700 border border-red-200 text-[10px] font-bold px-2 py-0.5 rounded-full">
              {overdueCount} overdue
            </span>
          )}
        </div>
        <ReplacementsSection items={decentHomesMeta} />
      </section>

    </div>
  );
}
