"use client"

import type { KeyboardEvent, ReactNode } from "react"
import Link from "next/link"
import { Frame, FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { Skeleton } from "@/components/ui/skeleton"
import { cn } from "@/lib/utils"
import { kpiCols } from "./kpi-cols"

export type KpiStatVariant = "default" | "warning" | "destructive"

/**
 * KPI tile — horizontal compact hybrid (icon left + label/Badge + value).
 * @see https://reui.io/preview/base/stats-12
 */
export type KpiStatItem = {
  id?: string
  label: ReactNode
  value: ReactNode
  hint?: ReactNode
  href?: string
  onSelect?: () => void
  onClick?: () => void
  selected?: boolean
  active?: boolean
  icon?: ReactNode
  iconClassName?: string
  variant?: KpiStatVariant
  footer?: ReactNode
}

export type KpiStatCardData = KpiStatItem & { id: string }

const DEFAULT_ICON_CLASS = "text-muted-foreground [&_svg]:text-current"

const VALUE_VARIANT_CLASS: Record<KpiStatVariant, string> = {
  default: "text-foreground",
  warning: "text-warning",
  destructive: "text-destructive",
}

function handleCardKeyDown(onActivate: () => void, event: KeyboardEvent<HTMLDivElement>) {
  if (event.key === "Enter" || event.key === " ") {
    event.preventDefault()
    onActivate()
  }
}

function resolveActivate(item: KpiStatItem): (() => void) | undefined {
  return item.onClick ?? item.onSelect
}

function isSelected(item: KpiStatItem): boolean {
  return Boolean(item.selected ?? item.active)
}

function resolveFooter(item: KpiStatItem): ReactNode {
  if (item.footer) return item.footer
  if (typeof item.hint === "string") {
    return (
      <Badge variant="outline" size="sm" className="max-w-[min(100%,11rem)] truncate">
        {item.hint}
      </Badge>
    )
  }
  if (item.hint) return item.hint
  return null
}

function KpiStatCardBody({ item }: { item: KpiStatItem }) {
  const footer = resolveFooter(item)
  const valueVariant = item.variant ?? "default"

  return (
    <div className="@container relative z-10 flex h-full min-w-0 items-start gap-3">
      {item.icon ? (
        <IconTile
          variant="elevated"
          aria-hidden="true"
          className={cn("size-10.5 shrink-0", item.iconClassName ?? DEFAULT_ICON_CLASS)}
        >
          {item.icon}
        </IconTile>
      ) : null}

      <div className="flex min-w-0 flex-1 flex-col gap-0.5">
        <div className="flex min-w-0 items-start justify-between gap-2">
          <div className="text-muted-foreground min-w-0 truncate text-sm font-medium">
            {item.label}
          </div>
          {footer ? (
            <div className="hidden min-w-0 max-w-[min(100%,11rem)] shrink-0 @[20rem]:block">
              {footer}
            </div>
          ) : null}
        </div>
        <div
          className={cn(
            "min-w-0 break-all text-2xl leading-none font-bold tabular-nums",
            VALUE_VARIANT_CLASS[valueVariant],
          )}
        >
          {item.value}
        </div>
        {footer ? (
          <div className="min-w-0 max-w-full @[20rem]:hidden">{footer}</div>
        ) : null}
      </div>
    </div>
  )
}

function panelClassName(item: KpiStatItem, className?: string) {
  const onActivate = resolveActivate(item)
  const clickable = Boolean(item.href || onActivate)
  const selected = isSelected(item)

  return cn(
    "relative isolate flex h-full min-w-0 flex-col",
    clickable &&
      "hover:bg-muted/40 focus-within:ring-ring cursor-pointer transition-colors focus-within:ring-2",
    selected && "ring-primary/30 bg-muted/30 ring-1",
    className,
  )
}

export function KpiStatCardTile({
  item,
  embedded = false,
  className,
}: {
  item: KpiStatItem
  embedded?: boolean
  className?: string
}) {
  const onActivate = resolveActivate(item)
  const panelClass = panelClassName(item, className)

  let panel: ReactNode

  if (item.href) {
    panel = (
      <FramePanel className={panelClass}>
        <Link href={item.href} className="focus-visible:outline-none">
          <KpiStatCardBody item={item} />
        </Link>
      </FramePanel>
    )
  } else if (onActivate) {
    panel = (
      <FramePanel
        className={panelClass}
        onClick={onActivate}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => handleCardKeyDown(onActivate, e)}
      >
        <KpiStatCardBody item={item} />
      </FramePanel>
    )
  } else {
    panel = (
      <FramePanel className={panelClass}>
        <KpiStatCardBody item={item} />
      </FramePanel>
    )
  }

  if (embedded) {
    return <Frame className="h-full ring-1 ring-foreground/10">{panel}</Frame>
  }

  return <Frame className="h-full">{panel}</Frame>
}

function KpiStatGridSkeleton({ count }: { count: number }) {
  return (
    <Frame className="@container w-full">
      <div className={cn("grid gap-2", kpiCols(count))}>
        {Array.from({ length: count }).map((_, index) => (
          <FramePanel key={index} className="flex items-start gap-3">
            <Skeleton className="size-10.5 shrink-0 rounded-lg" />
            <div className="flex min-w-0 flex-1 flex-col gap-1.5">
              <div className="flex items-center justify-between gap-2">
                <Skeleton className="h-4 w-20" />
                <Skeleton className="h-4.5 w-14 rounded-full" />
              </div>
              <Skeleton className="h-7 w-16" />
            </div>
          </FramePanel>
        ))}
      </div>
    </Frame>
  )
}

interface KpiStatGridProps {
  items?: KpiStatItem[]
  cards?: KpiStatCardData[]
  isLoading?: boolean
  emptyMessage?: ReactNode
  emptyIcon?: ReactNode
  className?: string
  skeletonCount?: number
  embedded?: boolean
  "aria-label"?: string
}

function KpiStatCardItem({ item }: { item: KpiStatItem }) {
  const onActivate = resolveActivate(item)
  const panelClass = panelClassName(item)

  if (item.href) {
    return (
      <FramePanel className={panelClass}>
        <Link href={item.href} className="focus-visible:outline-none">
          <KpiStatCardBody item={item} />
        </Link>
      </FramePanel>
    )
  }

  if (onActivate) {
    return (
      <FramePanel
        className={panelClass}
        onClick={onActivate}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => handleCardKeyDown(onActivate, e)}
      >
        <KpiStatCardBody item={item} />
      </FramePanel>
    )
  }

  return (
    <FramePanel className={panelClass}>
      <KpiStatCardBody item={item} />
    </FramePanel>
  )
}

/**
 * Hybrid KPI — horizontal compact layout (icon left).
 * Preview: https://reui.io/preview/base/stats-12
 */
export function KpiStatGrid({
  items,
  cards,
  isLoading = false,
  emptyMessage,
  emptyIcon,
  className,
  skeletonCount = 4,
  embedded = false,
  "aria-label": ariaLabel,
}: KpiStatGridProps) {
  if (isLoading) {
    return <KpiStatGridSkeleton count={skeletonCount} />
  }

  const list = items ?? cards ?? []

  if (list.length === 0 && (emptyMessage || emptyIcon)) {
    return (
      <Frame dense spacing="sm" className={cn("w-full", className)}>
        <FramePanel className="flex items-center gap-3 p-4">
          {emptyIcon}
          {emptyMessage ? (
            <p className="text-muted-foreground text-sm">{emptyMessage}</p>
          ) : null}
        </FramePanel>
      </Frame>
    )
  }

  if (embedded) {
    return (
      <section aria-label={ariaLabel} className={cn("@container w-full", className)}>
        <div className={cn("grid gap-2", kpiCols(list.length || 1))}>
          {list.map((item, index) => (
            <KpiStatCardTile key={kpiStatItemKey(item, index)} item={item} embedded />
          ))}
        </div>
      </section>
    )
  }

  return (
    <Frame className={cn("@container w-full min-w-0", className)} aria-label={ariaLabel}>
      <div className={cn("grid gap-2", kpiCols(list.length || 1))}>
        {list.map((item, index) => (
          <KpiStatCardItem key={kpiStatItemKey(item, index)} item={item} />
        ))}
      </div>
    </Frame>
  )
}

export function kpiStatItemKey(item: KpiStatItem, index: number): string {
  if (item.id) return item.id
  if (typeof item.label === "string") return item.label
  return `kpi-${index}`
}
