"use client";

import { useState } from "react";
import { Clock } from "lucide-react";
import type { DataQualityMetrics } from "../databaseFunctions";
import { DrillDownShelf, type DrillTarget } from "../components/DrillDownShelf";

const UNLOCK_MODULES = [
  {
    name: "Condition & compliance",
    unlocks:
      "Awaab's Law warnings, HHSRS Category 1 & 2 hazard counts and Decent Homes compliance.",
    columns: [
      "hazard_category",
      "hazard_severity",
      "survey_date",
      "decent_homes_pass",
    ],
  },
  {
    name: "Rent & valuation",
    unlocks:
      "Financial exposure, value uplift per scenario and payback framing in the investment ledger.",
    columns: ["rent_pa", "valuation", "valuation_date"],
  },
];

export function DataQualityClientArea({
  portfolioId,
  metrics,
}: {
  portfolioId: number;
  metrics: DataQualityMetrics;
}) {
  const [drill, setDrill] = useState<DrillTarget | null>(null);
  const [page, setPage] = useState(1);

  const {
    total,
    inDate,
    expired,
    estimated,
    likelyDowngrades,
    likelyUpgrades,
  } = metrics;
  const pct = (n: number) => (total > 0 ? Math.round((n / total) * 100) : 0);

  function open(t: DrillTarget) {
    setDrill(t);
    setPage(1);
  }

  const composition = [
    { label: "In date · " + inDate, value: inDate, color: "#14163d" },
    { label: "Expired · " + expired, value: expired, color: "#a07c42" },
    { label: "Estimated · " + estimated, value: estimated, color: "#c5cad8" },
  ];

  const issues = [
    {
      key: "estimated" as const,
      name: "Estimated EPCs",
      def: "No certificate exists; performance predicted from nearby homes of similar archetype.",
      count: estimated,
      impact:
        "These homes' SAP, bills and carbon are modelled, not certificated — they move averages and band counts.",
      good: false,
    },
    {
      key: "expired" as const,
      name: "Expired EPCs",
      def: "Real certificate, older than 10 years.",
      count: expired,
      impact:
        "Still counted as lodged, but the home may have changed since assessment. Re-assess before relying on these bands.",
      good: false,
    },
    {
      key: "likely-downgrade" as const,
      name: "Likely downgrades",
      def: "Lodged band sits above the effective band — a re-survey would likely certificate lower. Band movement only.",
      count: likelyDowngrades,
      impact:
        "The certificate on file is better than the home's true position, so compliance demonstrated by these EPCs is fragile.",
      good: false,
    },
    {
      key: "likely-upgrade" as const,
      name: "Likely upgrades",
      def: "Effective band sits above the lodged band — Landlord overrides or SAP 10.2 scoring improved the picture.",
      count: likelyUpgrades,
      impact:
        "These homes would likely certificate higher with a re-survey alone — the cheapest compliance moves in the portfolio.",
      good: true,
    },
  ];

  return (
    <div className="space-y-4" data-reporting>
      <div className="flex items-end justify-between gap-4">
        <div>
          <div className="text-[0.74rem] text-gray-600">
            Portfolios / Reporting
          </div>
          <h1 className="mt-0.5 text-[1.35rem] font-semibold tracking-tight text-brandblue">
            Data quality
          </h1>
        </div>
        <a
          href={`/portfolio/${portfolioId}/reporting`}
          className="inline-flex h-8 items-center rounded-lg border border-gray-200 bg-white px-3.5 text-sm font-medium"
        >
          ← Back to reporting
        </a>
      </div>

      {/* Evidence composition */}
      <section className="rounded-lg border border-gray-200 bg-white px-5 pb-5 pt-4">
        <h2 className="text-[0.88rem] font-semibold text-brandblue">
          EPC evidence
          <span className="ml-2 text-[0.74rem] font-normal text-gray-600">
            every home counted once, by strongest evidence
          </span>
        </h2>
        <div className="mt-4 flex h-[18px] overflow-hidden rounded">
          {composition.map((c) => (
            <span
              key={c.label}
              style={{
                width: `${total > 0 ? (c.value / total) * 100 : 0}%`,
                background: c.color,
              }}
            />
          ))}
        </div>
        <div className="mt-3 flex flex-wrap gap-4 text-[0.72rem] text-gray-500">
          {composition.map((c) => (
            <span key={c.label} className="flex items-center gap-1.5">
              <span
                className="inline-block h-2.5 w-2.5 rounded-sm"
                style={{ background: c.color }}
              />
              {c.label}
            </span>
          ))}
        </div>
      </section>

      {/* Issues */}
      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        {issues.map((issue, i) => (
          <div
            key={issue.key}
            className={`grid grid-cols-[210px_70px_1fr_130px] items-center gap-4 px-5 py-4 text-[0.83rem] ${
              i > 0 ? "border-t border-gray-100" : ""
            }`}
          >
            <div>
              <div className="font-semibold text-gray-900">{issue.name}</div>
              <div className="mt-0.5 text-[0.73rem] leading-snug text-gray-600">
                {issue.def}
              </div>
            </div>
            <div
              className={`text-right text-[1.1rem] font-semibold tabular-nums ${
                issue.good ? "text-[#0c6b4a]" : "text-brandblue"
              }`}
            >
              {issue.count}
              <span className="block text-[0.68rem] font-medium text-gray-600">
                {pct(issue.count)}%
              </span>
            </div>
            <div className="text-[0.78rem] leading-relaxed text-gray-500">
              {issue.impact}
            </div>
            <div className="text-right">
              <button
                onClick={() =>
                  open({
                    filter: issue.key,
                    title: issue.name,
                  })
                }
                className="text-[0.78rem] font-semibold text-midblue"
              >
                View homes →
              </button>
            </div>
          </div>
        ))}
      </section>

      {drill && (
        <DrillDownShelf
          portfolioId={portfolioId}
          target={drill}
          page={page}
          onPage={setPage}
          onClose={() => setDrill(null)}
        />
      )}

      {/* Not yet provided */}
      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        <h2 className="px-5 pt-4 text-[0.88rem] font-semibold text-brandblue">
          Not yet provided
          <span className="ml-2 text-[0.74rem] font-normal text-gray-600">
            data that unlocks new report sections
          </span>
        </h2>
        {UNLOCK_MODULES.map((m, i) => (
          <div
            key={m.name}
            className={`grid grid-cols-[180px_1fr_160px] items-start gap-5 px-5 py-4 ${
              i > 0
                ? "border-t border-gray-100"
                : "mt-2 border-t border-gray-100"
            }`}
          >
            <div>
              <div className="text-[0.83rem] font-semibold text-gray-900">
                {m.name}
              </div>
              <span className="mt-1.5 inline-block rounded bg-[#faf1e2] px-1.5 py-0.5 text-[0.64rem] font-bold text-[#9a5b10]">
                No data
              </span>
            </div>
            <div>
              <p className="text-[0.78rem] leading-relaxed text-gray-500">
                Unlocks {m.unlocks}
              </p>
              <div className="mt-2 flex flex-wrap items-center gap-1.5">
                {m.columns.map((c) => (
                  <span
                    key={c}
                    className="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-[0.66rem] text-gray-500"
                  >
                    {c}
                  </span>
                ))}
                <span className="text-[0.68rem] text-gray-600">
                  column set to confirm with the data team
                </span>
              </div>
            </div>
            <div className="flex items-center justify-end">
              <span className="inline-flex items-center gap-1.5 rounded-full bg-gray-50 px-2.5 py-1 text-[0.7rem] font-medium text-gray-400">
                <Clock className="h-3.5 w-3.5" />
                Coming soon
              </span>
            </div>
          </div>
        ))}
      </section>
    </div>
  );
}
