"use client";

import Link from "next/link";
import { motion, useReducedMotion } from "motion/react";
import { ArrowDownRight, ArrowUpRight } from "lucide-react";
import { cn } from "@/lib/utils";
import type { CommandCenterData } from "@/lib/queries/command-center";
import { Tooltip } from "@/components/ui/primitives";
import { Sparkline } from "@/components/ui/kpi-card";
import { CountUp } from "./count-up";
import { TiltCard } from "@/components/motion/tilt-card";
import { useChanged } from "@/components/motion/use-changed";
import { fmtMoney, fmtPercent } from "@/lib/format";

type H = CommandCenterData["hero"];

function Kpi({ label, value, format, delta, invert, hint, href, tone, spark, index }: { label: string; value: number; format: (v: number) => string; delta?: number | null; invert?: boolean; hint?: string; href: string; tone?: "positive" | "negative" | "warning" | "brand" | "muted"; spark?: number[]; index: number }) {
  const reduced = useReducedMotion();
  const changed = useChanged(value);
  const good = delta == null ? null : invert ? delta < 0 : delta > 0;
  return (
    <motion.div initial={reduced ? false : { opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ type: "spring", stiffness: 420, damping: 32, delay: 0.04 * index }} className="min-w-[150px]">
      <TiltCard className="h-full">
      <Link href={href} className={cn("group flex h-full flex-col justify-between rounded-xl border border-border bg-surface p-3.5 shadow-xs hairline-top transition-colors", changed && "animate-glow-flash border-primary/40")}>
        <div className="flex items-center gap-1">
          <p className="text-2xs font-semibold uppercase tracking-wider text-fg-muted">{label}</p>
          {hint ? (
            <Tooltip content={hint}>
              <span className="inline-flex size-3.5 items-center justify-center rounded-full border border-border-strong text-[9px] font-bold text-fg-subtle">?</span>
            </Tooltip>
          ) : null}
        </div>
        <div className="mt-2 flex items-end justify-between gap-2">
          <p className={cn("text-lg font-semibold tabular leading-none", tone === "positive" && "text-positive-600", tone === "negative" && "text-negative-600", tone === "warning" && "text-warning-600", tone === "brand" && "text-brand-700 dark:text-brand-300", tone === "muted" && "text-fg-muted")}>
            <CountUp value={value} format={format} />
          </p>
          {spark && spark.length > 1 ? <Sparkline data={spark} tone={good === null ? "primary" : good ? "positive" : "negative"} className="h-6 w-14 shrink-0 opacity-70 transition-opacity group-hover:opacity-100" height={24} /> : null}
        </div>
        {delta != null ? (
          <p className={cn("mt-1.5 flex items-center gap-0.5 text-2xs font-medium tabular", delta === 0 ? "text-fg-subtle" : good ? "text-positive-600" : "text-negative-600")}>
            {delta === 0 ? null : delta > 0 ? <ArrowUpRight className="size-3" /> : <ArrowDownRight className="size-3" />}
            {fmtPercent(Math.abs(delta), 1)} <span className="text-fg-subtle">vs prev.</span>
          </p>
        ) : (
          <p className="mt-1.5 text-2xs text-fg-subtle">&nbsp;</p>
        )}
      </Link>
      </TiltCard>
    </motion.div>
  );
}

export function KpiStrip({ hero: h, recovery, trend, currency, showProfit }: { hero: H; recovery: CommandCenterData["recovery"]; trend: CommandCenterData["trend"]; currency: string; showProfit: boolean }) {
  const m = (v: number) => fmtMoney(v, currency, { compact: true, whole: true });
  const s = (k: "revenue" | "profit" | "expenses" | "reservations" | "occupancy") => trend.map((t) => t[k]);
  let i = 0;
  return (
    <section aria-label="Financial KPIs" className="-mx-3 overflow-x-auto px-3 pb-1 scrollbar-none sm:mx-0 sm:px-0">
      <div className="grid min-w-[1100px] grid-cols-8 gap-3 sm:min-w-0 sm:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8">
        <Kpi index={i++} label="Net revenue" value={h.net} format={m} href="/financials" hint="Gross revenue − worker commissions" tone="brand" spark={s("revenue")} />
        {showProfit ? <Kpi index={i++} label="Profit" value={h.profit} format={m} delta={h.profitDelta} href="/financials" hint={`Revenue − expenses − commissions · ${fmtPercent(h.margin, 0)} margin`} tone={h.profit >= 0 ? "positive" : "negative"} spark={s("profit")} /> : <Kpi index={i++} label="Paid revenue" value={h.paid} format={m} href="/payments" tone="positive" />}
        <Kpi index={i++} label="Expenses" value={h.expenses} format={m} delta={h.expensesDelta} invert href="/expenses" tone="warning" spark={s("expenses")} />
        <Kpi index={i++} label="Outstanding" value={h.outstanding} format={m} href="/payments?filter=outstanding" hint="Reservation value not yet collected" tone={h.outstanding > 0 ? "warning" : "muted"} />
        <Kpi index={i++} label="Deposits" value={h.deposits} format={m} href="/payments" hint="Security deposits on reservations in the period" tone="muted" />
        <Kpi index={i++} label="Commissions" value={h.commissions} format={m} href="/commissions" hint="Worker commissions generated by reservations in the period" />
        <Kpi index={i++} label="Avg booking" value={h.avgBooking} format={m} href="/reports?type=reservations" hint="Average reservation value" />
        <Kpi index={i++} label="ADR" value={h.adr} format={m} href="/financials" hint="Average daily rate = revenue ÷ occupied nights" />
        <Kpi index={i++} label="RevPAA" value={h.revpaa} format={m} href="/financials" hint="Revenue per available apartment" />
        <Kpi index={i++} label="Occupancy" value={h.occupancy} format={(v) => fmtPercent(v, 0)} delta={h.occupancyDelta} href="/calendar" hint="Occupied nights ÷ available nights" spark={s("occupancy")} />
        <Kpi index={i++} label="Reservations" value={h.reservations} format={(v) => String(Math.round(v))} delta={h.reservationsDelta} href="/reservations" spark={s("reservations")} />
        <Kpi index={i++} label="Recovered" value={recovery.recoveredRevenue} format={m} href="/financials?tab=recovery" hint={`${recovery.recoveredNights} released nights re-sold in the period · ${fmtPercent(recovery.rebookRate, 0)} of releases re-booked (30d)`} tone="positive" />
      </div>
    </section>
  );
}
