"use client";

import * as React from "react";
import Link from "next/link";
import { ArrowDown, ArrowUp } from "lucide-react";
import { cn } from "@/lib/utils";
import { fmtMoney, fmtPercent } from "@/lib/format";

type Row = { id: string; code: string; name: string; reservations: number; nights: number; revenue: number; adr: number; occupancy: number; avgStay: number; cancelRate: number; upcoming30: number };
type Key = keyof Omit<Row, "id" | "code" | "name">;

const COLS: { key: Key; label: string; fmt: (v: number, cur: string) => string; money?: boolean; heat?: "good" | "bad" }[] = [
  { key: "revenue", label: "Revenue", fmt: (v, c) => fmtMoney(v, c, { compact: true, whole: true }), money: true, heat: "good" },
  { key: "occupancy", label: "Occupancy", fmt: (v) => fmtPercent(v, 0), heat: "good" },
  { key: "adr", label: "ADR", fmt: (v, c) => fmtMoney(v, c, { compact: true, whole: true }), money: true, heat: "good" },
  { key: "avgStay", label: "Avg stay", fmt: (v) => `${v.toFixed(1)} n` },
  { key: "reservations", label: "Reservations", fmt: (v) => String(v) },
  { key: "cancelRate", label: "Cancel rate", fmt: (v) => fmtPercent(v, 0), heat: "bad" },
  { key: "upcoming30", label: "Next 30 d", fmt: (v) => fmtPercent(v, 0), heat: "good" },
];

/** Sortable, heat-shaded apartment performance matrix. */
export function ApartmentMatrix({ rows, currency, money }: { rows: Row[]; currency: string; money: boolean }) {
  const [sort, setSort] = React.useState<{ key: Key; dir: "asc" | "desc" }>({ key: "revenue", dir: "desc" });
  const cols = COLS.filter((c) => money || !c.money);
  const data = React.useMemo(() => [...rows].sort((a, b) => (sort.dir === "desc" ? b[sort.key] - a[sort.key] : a[sort.key] - b[sort.key])), [rows, sort]);
  const max = Object.fromEntries(cols.map((c) => [c.key, Math.max(1, ...rows.map((r) => r[c.key]))])) as Record<Key, number>;
  return (
    <div className="overflow-x-auto scrollbar-thin">
      <table className="w-full text-sm">
        <thead className="text-left text-2xs font-semibold uppercase tracking-wider text-fg-muted">
          <tr>
            <th className="px-5 py-2">Apartment</th>
            {cols.map((c) => (
              <th key={c.key} className="px-3 py-2 text-right">
                <button type="button" onClick={() => setSort((s) => ({ key: c.key, dir: s.key === c.key && s.dir === "desc" ? "asc" : "desc" }))} className={cn("inline-flex items-center gap-1 hover:text-fg", sort.key === c.key && "text-fg")}>
                  {c.label}
                  {sort.key === c.key ? sort.dir === "desc" ? <ArrowDown className="size-3" /> : <ArrowUp className="size-3" /> : null}
                </button>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((r) => (
            <tr key={r.id} className="border-t border-border hover:bg-surface-2/60">
              <td className="px-5 py-2">
                <Link href={`/apartments/${r.id}`} className="hover:text-primary">
                  <span className="font-mono text-xs font-semibold">{r.code}</span> <span className="text-fg-muted">{r.name}</span>
                </Link>
              </td>
              {cols.map((c) => {
                const ratio = r[c.key] / max[c.key];
                const tint = c.heat === "good" ? `color-mix(in oklab, var(--color-positive-500) ${Math.round(ratio * 22)}%, transparent)` : c.heat === "bad" ? `color-mix(in oklab, var(--color-negative-500) ${Math.round(ratio * 22)}%, transparent)` : undefined;
                return (
                  <td key={c.key} className="px-3 py-2 text-right tabular" style={{ background: tint }}>
                    {c.fmt(r[c.key], currency)}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
