"use client";

import { useState } from "react";
import { Panel } from "./primitives";
import { PROPERTY_TYPE_LABELS } from "@/lib/epc/labels";
import type { AgeBandCount, PropertyTypeCount } from "../types";

type Tab = "age" | "type";

/**
 * Stock breakdown panel (Screen A) — age and property-type cuts as one-click
 * tabs sharing the ladder's row rhythm. Local authority is a future tab
 * pending a coverage check.
 */
export function StockBreakdown({
  ageBands,
  propertyTypes,
}: {
  ageBands: AgeBandCount[];
  propertyTypes: PropertyTypeCount[];
}) {
  const [tab, setTab] = useState<Tab>("age");

  const rows =
    tab === "age"
      ? ageBands.map((a) => ({ label: a.age_band, count: a.count }))
      : propertyTypes.map((p) => ({
          label: p.type ? (PROPERTY_TYPE_LABELS[p.type] ?? p.type) : "Unknown",
          count: p.count,
        }));

  const max = Math.max(1, ...rows.map((r) => r.count));

  return (
    <Panel
      title="Stock breakdown"
      action={
        <span className="inline-flex gap-3.5 text-[0.76rem] font-medium">
          {(["age", "type"] as Tab[]).map((t) => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className={`pb-0.5 ${
                tab === t
                  ? "border-b-2 border-brandblue text-brandblue"
                  : "text-gray-600"
              }`}
            >
              {t === "age" ? "Age" : "Type"}
            </button>
          ))}
        </span>
      }
    >
      <div className="grid grid-cols-[88px_1fr_40px] items-center gap-x-3 gap-y-2.5 text-[0.76rem] text-gray-500">
        {rows.map((r) => (
          <div key={r.label} className="contents">
            <span className="truncate">{r.label}</span>
            <span>
              <span
                className="block h-[18px] rounded bg-brandblue opacity-80"
                style={{ width: `${(r.count / max) * 100}%` }}
              />
            </span>
            <span className="text-right font-medium tabular-nums text-gray-900">
              {r.count}
            </span>
          </div>
        ))}
      </div>
    </Panel>
  );
}
