import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Link } from "@tanstack/react-router";
import { TrendingDown, TrendingUp, Gift, Activity, ChevronRight } from "lucide-react";
import { getHomeInsights, type HomeInsights } from "@/lib/insights.functions";
import { txTypeLabel } from "@/lib/format";
import { Money } from "@/components/Money";
import { cn } from "@/lib/utils";

function relTime(iso: string) {
  const s = Math.max(1, Math.floor((Date.now() - new Date(iso).getTime()) / 1000));
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

export function useHomeInsights() {
  const fetchInsights = useServerFn(getHomeInsights);
  return useQuery<HomeInsights>({
    queryKey: ["home-insights"],
    queryFn: () => fetchInsights(),
    refetchInterval: 30_000,
    staleTime: 10_000,
  });
}

export function InsightsStrip() {
  const { data } = useHomeInsights();
  const cards = [
    { label: "Spent this month", value: data?.monthSpent ?? 0, icon: TrendingDown, tone: "text-destructive" },
    { label: "Money received", value: data?.monthReceived ?? 0, icon: TrendingUp, tone: "text-success" },
    { label: "Cashback earned", value: data?.cashback ?? 0, icon: Gift, tone: "text-primary" },
  ];
  return (
    <div className="grid grid-cols-3 gap-2">
      {cards.map(({ label, value, icon: Icon, tone }) => (
        <div
          key={label}
          className="rounded-2xl bg-card/80 p-2.5 shadow-card ring-1 ring-border/40 backdrop-blur"
        >
          <Icon className={cn("h-4 w-4", tone)} />
          <Money value={value} className="mt-1.5 block truncate text-[13px] font-extrabold tracking-tight" />
          <div className="text-[9.5px] font-medium uppercase tracking-wide text-muted-foreground">{label}</div>
        </div>
      ))}
    </div>
  );
}

/** Personal live activity feed — real account events, tappable. */
export function ActivityFeed() {
  const { data } = useHomeInsights();
  const items = (data?.recent ?? []).slice(0, 2);

  return (
    <section className="overflow-hidden rounded-2xl bg-card shadow-card ring-1 ring-border/50">
      <div className="flex items-center gap-2 border-b border-border/60 px-3 py-2.5">
        <span className="relative flex h-2 w-2">
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
        </span>
        <Activity className="h-3.5 w-3.5 text-primary" />
        <h2 className="text-[11px] font-bold uppercase tracking-wider">Billsline Live</h2>
        <Link to="/app/history" className="ml-auto text-[11px] font-semibold text-primary">
          View all
        </Link>
      </div>

      {items.length === 0 ? (
        <p className="px-3 py-5 text-center text-xs text-muted-foreground">
          Your activity will appear here once you make your first transaction.
        </p>
      ) : (
        <ul className="divide-y divide-border/50">
          {items.map((t) => (
            <li key={t.reference}>
              <Link
                to="/app/tx/$ref"
                params={{ ref: t.reference }}
                className="flex items-center gap-3 px-3 py-2.5 transition hover:bg-muted/50"
              >
                <span
                  className={cn(
                    "grid h-8 w-8 shrink-0 place-items-center rounded-full text-[11px] font-bold",
                    t.direction === "in" ? "bg-success/15 text-success" : "bg-primary/10 text-primary",
                  )}
                >
                  {t.direction === "in" ? "+" : "-"}
                </span>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-xs font-semibold">
                    {t.description ?? txTypeLabel[t.type] ?? t.type}
                  </div>
                  <div className="text-[10px] text-muted-foreground">
                    {relTime(t.created_at)} · {t.status}
                  </div>
                </div>
                <Money value={t.amount} className="text-xs font-bold" />
                <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
              </Link>
            </li>
          ))}
        </ul>
      )}

      {items.length > 0 && (
        <Link
          to="/app/history"
          className="flex items-center justify-center gap-1 border-t border-border/60 py-2.5 text-[11px] font-bold uppercase tracking-wide text-primary transition hover:bg-muted/50"
        >
          View all transactions <ChevronRight className="h-3.5 w-3.5" />
        </Link>
      )}
    </section>
  );
}
