import Link from "next/link";
import { ArrowRight, TrendingDown, TrendingUp } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { DashboardCard } from "@/types/dashboard";

/**
 * The snapshot tiles at the top of the dashboard, built on the shadcn `Card`.
 *
 * Rebuilt around the numbers. Each tile previously stacked two blurred colour
 * blobs, a translucent white gradient wash, `backdrop-blur-xl`, a shadow that
 * grew to `2xl` on hover and a 2px lift over 500ms — five effects between the
 * reader and a currency figure, and the frosted background made the value's
 * contrast depend on whatever it happened to sit over.
 *
 * Now: a flat card, one hairline border, the metric as the loudest element, and
 * a single quick hover transition. The per-card accent survives as a small icon
 * tile, which is where it actually helps you tell the tiles apart.
 */

const TONE_CLASS: Record<DashboardCard["tone"], string> = {
  positive: "text-success",
  negative: "text-destructive",
  neutral: "text-muted-foreground",
};

function getToneClass(tone: DashboardCard["tone"]): string {
  return TONE_CLASS[tone] ?? TONE_CLASS.neutral;
}

/** Grid/carousel geometry, shared by the real tiles and their skeleton so the
 *  layout does not shift when data arrives.
 *
 *  `auto-fit` rather than a fixed column count: the card set is driven by the
 *  API (six today, but it varies by which asset classes an account holds), so
 *  hardcoding `grid-cols-6` would strand a lone card on a second row the moment
 *  that number changes — which is exactly what a fixed `2xl:grid-cols-5` was
 *  doing to the sixth tile. Each column takes at least 200px and they share the
 *  row equally, so any count fills one line until it genuinely cannot fit. */
const GRID_CLASS =
  "-mx-4 flex snap-x snap-mandatory gap-3 overflow-x-auto px-4 pb-2 " +
  "hide-scrollbar sm:mx-0 sm:grid sm:grid-cols-2 sm:gap-4 sm:overflow-visible " +
  "sm:px-0 sm:pb-0 lg:grid-cols-3 xl:[grid-template-columns:repeat(auto-fit,minmax(200px,1fr))]";

/** Placeholder shown during the dashboard's first load. */
export function DashboardCardsSkeleton({ count = 5 }: { count?: number }) {
  return (
    <div className={GRID_CLASS} aria-hidden>
      {Array.from({ length: count }).map((_, i) => (
        <Card key={i} className="min-w-[240px] gap-0 py-4 sm:min-w-0">
          <CardContent className="px-4">
            <div className="flex items-start justify-between gap-3">
              <Skeleton className="h-3 w-24" />
              <Skeleton className="size-8 rounded-md" />
            </div>
            <Skeleton className="mt-4 h-7 w-32" />
            <Skeleton className="mt-2 h-3 w-20" />
            <div className="mt-4 space-y-2 border-t border-border pt-3">
              <Skeleton className="h-3 w-full" />
              <Skeleton className="h-3 w-4/5" />
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

interface DashboardCardsProps {
  cards: DashboardCard[];
}

export function DashboardCards({ cards }: DashboardCardsProps) {
  return (
    // Horizontal snap carousel on phones, a real grid from sm up. The negative
    // margin lets the carousel bleed to the screen edge so the last card does
    // not look clipped mid-scroll.
    <div className={GRID_CLASS}>
      {cards.map((card) => (
        <DashboardCardTile key={card.key} card={card} />
      ))}
    </div>
  );
}

interface DashboardCardTileProps {
  card: DashboardCard;
}

function DashboardCardTile({ card }: DashboardCardTileProps) {
  const Icon = card.icon;
  const toneClass = getToneClass(card.tone);
  const TrendIcon =
    card.tone === "positive" ? TrendingUp : card.tone === "negative" ? TrendingDown : null;

  return (
    <Card
      className={cn(
        "min-w-[240px] snap-start gap-0 py-4 transition-shadow sm:min-w-0",
        "hover:border-border-strong hover:shadow-md"
      )}
    >
      <CardContent className="flex h-full flex-col px-4">
        <div className="flex items-start justify-between gap-3">
          <p className="oxy-eyebrow min-w-0 truncate">{card.title}</p>
          <span
            className={cn(
              "inline-flex size-8 shrink-0 items-center justify-center rounded-md",
              card.accent.icon
            )}
            aria-hidden
          >
            <Icon className="size-4" />
          </span>
        </div>

        <div className="mt-3 flex items-baseline gap-1.5">
          <p className="text-2xl font-semibold tabular-nums tracking-tight text-foreground">
            {card.metric}
          </p>
          <span className="text-xs font-medium text-muted-foreground">
            {card.currency}
          </span>
        </div>

        {card.description && (
          <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
            {card.description}
          </p>
        )}

        {card.delta && (
          /* Direction is carried by an arrow as well as the colour, so the
             positive/negative distinction survives without colour vision. */
          <p className={cn("mt-1.5 flex items-center gap-1 text-xs font-semibold", toneClass)}>
            {TrendIcon && <TrendIcon className="size-3.5 shrink-0" aria-hidden />}
            {card.delta}
          </p>
        )}

        {card.breakdown.length > 0 && (
          <dl className="mt-3 space-y-1.5 border-t border-border pt-3">
            {card.breakdown.map((item) => (
              <div key={item.label} className="flex items-center justify-between gap-3">
                <dt className="min-w-0 truncate text-xs text-muted-foreground">
                  {item.label}
                </dt>
                <dd className="shrink-0 text-xs font-semibold tabular-nums text-foreground">
                  {item.value}
                </dd>
              </div>
            ))}
          </dl>
        )}

        <Link
          href={card.href}
          className="group mt-auto inline-flex items-center gap-1 pt-4 text-xs font-semibold text-muted-foreground transition-colors hover:text-primary"
        >
          View details
          <ArrowRight
            className="size-3.5 transition-transform group-hover:translate-x-0.5"
            aria-hidden
          />
          <span className="sr-only">for {card.title}</span>
        </Link>
      </CardContent>
    </Card>
  );
}
