"use client";

import { useQuery } from "@tanstack/react-query";
import { X } from "lucide-react";
import { EpcChip } from "./primitives";
import { formatNumber } from "@/app/utils";
import {
  serializeTagFilter,
  emptyTagFilter,
  type TagFilter,
} from "@/lib/reporting/viewState";

/**
 * The drill-down shelf (Screen C) — one pattern for every count on the
 * page. Opens beneath the chart, lists the homes behind the clicked figure
 * from /reporting/properties, and deep-links into the property table.
 */

export interface DrillTarget {
  filter:
    | "band"
    | "estimated"
    | "expired"
    | "likely-downgrade"
    | "likely-upgrade"
    | "measure";
  band?: string;
  scenarioId?: number;
  measureType?: string;
  title: string;
  chipBand?: string;
}

interface PropertyRow {
  id: number;
  address: string | null;
  postcode: string | null;
  epcBand: string | null;
  sap: number | null;
  bills: number | null;
  carbon: number | null;
  provenance: string;
}

interface DrillResponse {
  properties: PropertyRow[];
  total: number;
  page: number;
  pageSize: number;
}

// A compact preview — the shelf is a first look, not the full table.
const DRILL_PAGE_SIZE = 8;

function buildQuery(
  portfolioId: number,
  t: DrillTarget,
  page: number,
  tags: TagFilter,
) {
  const p = new URLSearchParams({
    filter: t.filter,
    page: String(page),
    pageSize: String(DRILL_PAGE_SIZE),
  });
  if (t.band) p.set("band", t.band);
  if (t.scenarioId != null) p.set("scenarioId", String(t.scenarioId));
  if (t.measureType) p.set("measureType", t.measureType);
  // The drill list must show the same tagged subset as the figure it opened.
  serializeTagFilter(tags, p);
  return `/api/portfolio/${portfolioId}/reporting/properties?${p.toString()}`;
}

export function DrillDownShelf({
  portfolioId,
  target,
  page,
  onPage,
  onClose,
  tags,
}: {
  portfolioId: number;
  target: DrillTarget;
  page: number;
  onPage: (p: number) => void;
  onClose: () => void;
  /** View-wide tag filter; omitted (e.g. data-quality drill) → no tag scoping. */
  tags?: TagFilter;
}) {
  const tagFilter = tags ?? emptyTagFilter();
  const { data, isLoading, isError } = useQuery<DrillResponse>({
    queryKey: ["reporting-drill", portfolioId, target, page, tagFilter],
    queryFn: () =>
      fetch(buildQuery(portfolioId, target, page, tagFilter)).then((r) => {
        if (!r.ok) throw new Error("Failed to load homes");
        return r.json();
      }),
    keepPreviousData: true,
  });

  const total = data?.total ?? 0;
  const pageSize = data?.pageSize ?? DRILL_PAGE_SIZE;
  const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
  const to = Math.min(page * pageSize, total);

  // The property table (the portfolio home) filters client-side and doesn't
  // read URL params, so we navigate to it without a filter — the shelf itself
  // is the filtered view. (A URL-driven table filter is a separate follow-up.)
  const tableHref = `/portfolio/${portfolioId}`;

  return (
    <div
      id="reporting-drill-shelf"
      className="mt-4 overflow-hidden rounded-lg border border-midblue bg-white"
    >
      <header className="flex items-center gap-3 border-b border-gray-100 px-5 py-3.5">
        <span className="flex items-center gap-2 text-[0.95rem] font-semibold text-brandblue">
          {target.chipBand && <EpcChip band={target.chipBand} size="md" />}
          {target.title}
          {total > 0 && (
            <span className="font-normal text-gray-600">· {total} homes</span>
          )}
        </span>
        <button
          type="button"
          onClick={onClose}
          className="ml-auto inline-flex items-center gap-1 text-[0.78rem] text-gray-600 hover:text-gray-900"
        >
          Collapse <X className="h-3.5 w-3.5" />
        </button>
      </header>

      {isLoading && !data && (
        <div className="px-5 py-8 text-center text-sm text-gray-600">
          Loading homes…
        </div>
      )}
      {isError && (
        <div
          role="alert"
          className="px-5 py-8 text-center text-sm text-red-600"
        >
          Could not load these homes.
        </div>
      )}

      {data && (
        <div className="overflow-x-auto">
          <table className="w-full text-[0.82rem]">
            <thead>
              <tr className="text-[0.68rem] uppercase tracking-wide text-gray-600">
                <th className="px-5 py-2 text-left font-bold">Address</th>
                <th className="px-5 py-2 text-left font-bold">EPC</th>
                <th className="px-5 py-2 text-right font-bold">SAP</th>
                <th className="px-5 py-2 text-right font-bold">Bills /yr</th>
                <th className="px-5 py-2 text-right font-bold">CO₂ /yr</th>
                <th className="px-5 py-2" />
              </tr>
            </thead>
            <tbody>
              {data.properties.map((p) => (
                <tr key={p.id} className="border-t border-gray-100">
                  <td className="px-5 py-2 font-medium text-gray-900">
                    {p.address ?? "—"}
                    <span className="block text-[0.7rem] font-normal text-gray-600">
                      {p.postcode ?? ""}
                      {p.provenance === "estimated" && " · estimated"}
                    </span>
                  </td>
                  <td className="px-5 py-2">
                    {p.epcBand ? <EpcChip band={p.epcBand} size="sm" /> : "—"}
                  </td>
                  <td className="px-5 py-2 text-right tabular-nums">
                    {p.sap != null ? Math.round(p.sap) : "—"}
                  </td>
                  <td className="px-5 py-2 text-right tabular-nums">
                    {p.bills != null ? `£${formatNumber(p.bills)}` : "—"}
                  </td>
                  <td className="px-5 py-2 text-right tabular-nums">
                    {p.carbon != null ? `${p.carbon.toFixed(1)} t` : "—"}
                  </td>
                  <td className="px-5 py-2 text-right">
                    <a
                      href={`/portfolio/${portfolioId}/building-passport/${p.id}`}
                      className="whitespace-nowrap font-semibold text-midblue"
                    >
                      Open →
                    </a>
                  </td>
                </tr>
              ))}
              {data.properties.length === 0 && (
                <tr>
                  <td
                    colSpan={6}
                    className="px-5 py-8 text-center text-sm text-gray-600"
                  >
                    No homes match this filter.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      <footer className="flex items-center justify-between gap-2 border-t border-gray-100 bg-gray-50 px-5 py-3">
        <span className="text-[0.76rem] text-gray-600">
          {from}–{to} of {total}
        </span>
        <div className="flex items-center gap-2">
          <button
            type="button"
            disabled={page <= 1}
            onClick={() => onPage(page - 1)}
            className="rounded-md border border-gray-200 px-3 py-1.5 text-[0.8rem] font-medium disabled:opacity-40"
          >
            Prev
          </button>
          <button
            type="button"
            disabled={to >= total}
            onClick={() => onPage(page + 1)}
            className="rounded-md border border-gray-200 px-3 py-1.5 text-[0.8rem] font-medium disabled:opacity-40"
          >
            Next
          </button>
          <a
            href={tableHref}
            className="rounded-md border border-brandblue bg-brandblue px-3 py-1.5 text-[0.8rem] font-medium text-white"
          >
            Open in property table →
          </a>
        </div>
      </footer>
    </div>
  );
}
