/**
 * DashboardStatCard (Sorbet Studio)
 *
 * The shared stat/metric card. Clean white panel, warm border, no icons —
 * the number is the point. Trend renders as a tinted pill; up/down semantics
 * live in the pill text color only.
 *
 * `icon`, `iconColor`, and `tooltip` are still accepted so existing call sites
 * compile, but they intentionally render nothing: decorative per-metric icons
 * and info-circles explaining obvious metrics were removed in the redesign.
 *
 * @example
 * <DashboardStatCard
 *   title="Orders"
 *   value={1234}
 *   subtitle="772 total items"
 *   trend={{ value: 12.5 }}
 * />
 */

import React from "react";
import { type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { STUDIO_COLORS } from "@/lib/dashboard/designTokens";

// =============================================================================
// TYPES
// =============================================================================

export type TrendDirection = "up" | "down" | "neutral";
export type CardSize = "default" | "compact" | "large";

export interface TrendProps {
  /** The percentage or absolute change value */
  value: number;
  /** Optional label to show after the trend (e.g., "vs last month") */
  label?: string;
  /** Whether a higher value is better (affects color). Defaults to true. */
  moreIsBetter?: boolean;
  /** Suffix for the trend value (defaults to "%"). Use "" for no suffix. */
  suffix?: string;
}

export interface DashboardStatCardProps {
  /** Card title/label */
  title: string;
  /** The main value to display (can be string for formatted values or number) */
  value: string | number;
  /** Optional prefix for the value (e.g., "$") */
  valuePrefix?: string;
  /** Optional suffix for the value (e.g., "/day", "%") */
  valueSuffix?: string;
  /** Optional subtitle or description (can be string or JSX) */
  subtitle?: React.ReactNode;
  /** Optional trend indicator */
  trend?: TrendProps;
  /** Accepted for compatibility; not rendered in the Studio design */
  icon?: LucideIcon;
  /** Accepted for compatibility; not rendered in the Studio design */
  iconColor?: string;
  /** Card size variant */
  size?: CardSize;
  /** Additional className for the card */
  className?: string;
  /** Click handler for interactive cards */
  onClick?: () => void;
  /** Loading state */
  loading?: boolean;
  /** Accepted for compatibility; not rendered in the Studio design */
  tooltip?: string;
  /** Additional content to render below the main value */
  children?: React.ReactNode;
}

// =============================================================================
// TREND PILL
// =============================================================================

interface TrendPillProps extends TrendProps {
  size?: CardSize;
}

export const TrendPill: React.FC<TrendPillProps> = ({
  value,
  label,
  moreIsBetter = true,
  suffix = "%",
}) => {
  if (value === 0) return null;
  const isGood = (value > 0) === moreIsBetter;
  const formattedValue = suffix === "%" ? Math.abs(value).toFixed(1) : Math.abs(value).toString();

  return (
    <span className="inline-flex items-center gap-1">
      <span
        className="rounded-full px-1.5 py-px text-[10.5px] font-bold whitespace-nowrap"
        style={{
          background: isGood ? "rgba(35,122,77,.09)" : "rgba(179,80,63,.09)",
          color: isGood ? STUDIO_COLORS.up : STUDIO_COLORS.down,
        }}
      >
        {value > 0 ? "↑" : "↓"} {formattedValue}
        {suffix}
      </span>
      {label && (
        <span className="text-[11px]" style={{ color: STUDIO_COLORS.muted }}>
          {label}
        </span>
      )}
    </span>
  );
};

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export const DashboardStatCard: React.FC<DashboardStatCardProps> = ({
  title,
  value,
  valuePrefix,
  valueSuffix,
  subtitle,
  trend,
  size = "default",
  className,
  onClick,
  loading = false,
  children,
}) => {
  const valueClass =
    size === "large"
      ? "text-[24px]"
      : size === "compact"
        ? "text-[17px]"
        : "text-[20px]";

  const cardClass = cn(
    "rounded-[14px] border bg-card px-3.5 py-3",
    onClick &&
      "cursor-pointer transition-colors duration-150 hover:bg-surface-subtle focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
    className
  );
  const cardStyle = { borderColor: STUDIO_COLORS.border };

  // Loading state
  if (loading) {
    return (
      <div className={cn(cardClass, "min-h-[92px]")} style={cardStyle}>
        <div className="h-3.5 w-20 animate-pulse rounded bg-muted" />
        <div className="mt-2.5 h-6 w-28 animate-pulse rounded bg-muted" />
        {subtitle && <div className="mt-2 h-3.5 w-24 animate-pulse rounded bg-muted/60" />}
      </div>
    );
  }

  return (
    <div
      className={cn(cardClass, "min-h-[92px]")}
      style={cardStyle}
      onClick={onClick}
      onKeyDown={
        onClick
          ? (event) => {
              if (event.key === "Enter" || event.key === " ") {
                event.preventDefault();
                onClick();
              }
            }
          : undefined
      }
      role={onClick ? "button" : undefined}
      tabIndex={onClick ? 0 : undefined}
    >
      <h4 className="text-[11px] font-semibold" style={{ color: STUDIO_COLORS.muted }}>
        {title}
      </h4>
      <div className="mt-0.5 flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
        <span
          className={cn(valueClass, "font-bold tracking-tight tabular-nums")}
          style={{ color: STUDIO_COLORS.ink }}
        >
          {valuePrefix}
          {typeof value === "number" ? value.toLocaleString() : value}
          {valueSuffix}
        </span>
        {trend && (
          <TrendPill
            value={trend.value}
            label={trend.label}
            moreIsBetter={trend.moreIsBetter}
            suffix={trend.suffix}
          />
        )}
      </div>
      {subtitle && (
        <div className="mt-0.5 text-[11.5px]" style={{ color: STUDIO_COLORS.muted }}>
          {subtitle}
        </div>
      )}
      {children}
    </div>
  );
};

// =============================================================================
// SKELETON VARIANT
// =============================================================================

export interface DashboardStatCardSkeletonProps {
  size?: CardSize;
  hasIcon?: boolean;
  hasSubtitle?: boolean;
  className?: string;
}

export const DashboardStatCardSkeleton: React.FC<DashboardStatCardSkeletonProps> = ({
  hasSubtitle = true,
  className,
}) => (
  <div
    className={cn("min-h-[92px] rounded-[14px] border bg-card px-3.5 py-3", className)}
    style={{ borderColor: STUDIO_COLORS.border }}
  >
    <div className="h-3.5 w-20 animate-pulse rounded bg-muted" />
    <div className="mt-2.5 h-6 w-28 animate-pulse rounded bg-muted" />
    {hasSubtitle && <div className="mt-2 h-3.5 w-24 animate-pulse rounded bg-muted/60" />}
  </div>
);

export default DashboardStatCard;
