/**
 * DashboardStatCardMini
 *
 * A compact, visually prominent stat card with gradient backgrounds.
 * Designed for hero metrics or dashboard headers where cards need to stand out.
 *
 * @example
 * <DashboardStatCardMini
 *   title="Total Revenue"
 *   value="$12,345"
 *   gradient="emerald"
 *   icon={DollarSign}
 *   trend={{ value: 12.5, label: "vs last month" }}
 * />
 */

import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { ArrowUp, ArrowDown, Minus, Info, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";

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

export type GradientVariant =
  | "slate"
  | "emerald"
  | "blue"
  | "purple"
  | "violet"
  | "amber"
  | "orange"
  | "rose"
  | "cyan"
  | "sky"
  | "custom";

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 DashboardStatCardMiniProps {
  /** Card title/label */
  title: string;
  /** The main value to display */
  value: string | number;
  /** Optional prefix for the value (e.g., "$") */
  valuePrefix?: string;
  /** Optional suffix for the value (e.g., "%") */
  valueSuffix?: string;
  /** Optional subtitle or description (can be string or JSX) */
  subtitle?: React.ReactNode;
  /** Optional trend indicator */
  trend?: TrendProps;
  /** Optional icon component */
  icon?: LucideIcon;
  /** Icon background color class (e.g., "bg-emerald-500/20") */
  iconBackground?: string;
  /** Gradient preset or "custom" to use className */
  gradient?: GradientVariant;
  /** Additional className (use with gradient="custom" for custom backgrounds) */
  className?: string;
  /** Click handler */
  onClick?: () => void;
  /** Loading state */
  loading?: boolean;
  /** Tooltip text shown via info icon next to title */
  tooltip?: string;
  /** Additional content to render below the main value */
  children?: React.ReactNode;
}

// =============================================================================
// GRADIENT PRESETS
// =============================================================================

const GRADIENT_PRESETS: Record<GradientVariant, string> = {
  slate: "bg-gradient-to-br from-slate-800/80 to-slate-700/60",
  emerald: "bg-gradient-to-br from-emerald-900/80 to-emerald-700/40",
  blue: "bg-gradient-to-br from-blue-900/80 to-blue-700/40",
  purple: "bg-gradient-to-br from-purple-900/80 to-purple-700/40",
  violet: "bg-gradient-to-br from-violet-900/80 to-violet-700/40",
  amber: "bg-gradient-to-br from-amber-800/80 to-amber-600/40",
  orange: "bg-gradient-to-br from-orange-900/80 to-orange-700/40",
  rose: "bg-gradient-to-br from-rose-900/80 to-rose-700/40",
  cyan: "bg-gradient-to-br from-cyan-900/80 to-cyan-700/40",
  sky: "bg-gradient-to-br from-sky-900/80 to-sky-700/40",
  custom: "",
};

// =============================================================================
// HELPER COMPONENTS
// =============================================================================

/**
 * Get trend colors optimized for dark gradient backgrounds
 */
const getTrendColors = (value: number, moreIsBetter: boolean = true): string => {
  const isPositive = value > 0;
  const isGood = moreIsBetter ? isPositive : !isPositive;

  if (value === 0) {
    return "text-gray-300";
  }
  return isGood ? "text-emerald-300" : "text-rose-300";
};

interface TrendIndicatorProps {
  value: number;
  label?: string;
  moreIsBetter?: boolean;
  suffix?: string;
}

const TrendIndicator: React.FC<TrendIndicatorProps> = ({
  value,
  label,
  moreIsBetter = true,
  suffix = "%",
}) => {
  const colorClass = getTrendColors(value, moreIsBetter);
  const IconComponent = value > 0 ? ArrowUp : value < 0 ? ArrowDown : Minus;

  // Format the value - round to integer for compact display (preserves sign for negatives)
  const formattedValue = Math.round(value);

  return (
    <span className={cn("flex items-center gap-0.5 text-sm font-semibold", colorClass)}>
      <IconComponent className="h-4 w-4" />
      {value > 0 ? "+" : ""}
      {formattedValue}
      {suffix}
      {label && <span className="text-gray-300 font-normal ml-1">{label}</span>}
    </span>
  );
};

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

export const DashboardStatCardMini: React.FC<DashboardStatCardMiniProps> = ({
  title,
  value,
  valuePrefix,
  valueSuffix,
  subtitle,
  trend,
  icon: Icon,
  iconBackground,
  gradient = "slate",
  className,
  onClick,
  loading = false,
  tooltip,
  children,
}) => {
  const gradientClass = gradient === "custom" ? "" : GRADIENT_PRESETS[gradient];

  // Loading state
  if (loading) {
    return (
      <Card
        className={cn(
          gradientClass,
          "backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20",
          className
        )}
      >
        <CardHeader className="flex flex-row items-center justify-between space-y-0 px-4 py-3">
          <div className="h-4 w-20 bg-white/20 animate-pulse rounded" />
          {Icon && <div className="h-9 w-9 bg-white/20 animate-pulse rounded-full" />}
        </CardHeader>
        <CardContent className="p-4 pt-1">
          <div className="h-9 w-28 bg-white/20 animate-pulse rounded mb-2" />
          {subtitle && <div className="h-4 w-24 bg-white/10 animate-pulse rounded" />}
        </CardContent>
      </Card>
    );
  }

  return (
    <Card
      className={cn(
        gradientClass,
        "backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20",
        onClick && "cursor-pointer transition-all hover:brightness-110 hover:ring-white/[0.12]",
        className
      )}
      onClick={onClick}
    >
      <CardHeader className="flex flex-row items-center justify-between space-y-0 px-4 py-3">
        <div className="flex items-center gap-1.5">
          <CardTitle className="text-xs font-medium text-gray-100 uppercase tracking-wide">
            {title}
          </CardTitle>
          {tooltip && (
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  className="text-gray-400 hover:text-gray-200 transition-colors"
                  onClick={(e) => e.stopPropagation()}
                >
                  <Info className="h-3.5 w-3.5" />
                </button>
              </TooltipTrigger>
              <TooltipContent side="top" className="max-w-xs">
                <p className="text-sm">{tooltip}</p>
              </TooltipContent>
            </Tooltip>
          )}
        </div>
        {Icon && (
          <div className="relative p-2">
            {iconBackground && (
              <div
                className={cn("absolute inset-0 rounded-full", iconBackground)}
              />
            )}
            <Icon className="h-4 w-4 text-white relative" />
          </div>
        )}
      </CardHeader>
      <CardContent className="p-4 pt-1">
        <div className="text-3xl font-extrabold text-white">
          {valuePrefix}
          {typeof value === "number" ? value.toLocaleString() : value}
          {valueSuffix && (
            <span className="text-xl text-gray-300">{valueSuffix}</span>
          )}
        </div>
        {(subtitle || trend) && (
          <div className="flex flex-wrap items-center justify-between gap-0 mt-3">
            {subtitle && (
              <span className="text-sm font-semibold text-gray-200">
                {subtitle}
              </span>
            )}
            {trend && (
              <TrendIndicator
                value={trend.value}
                label={trend.label}
                moreIsBetter={trend.moreIsBetter}
                suffix={trend.suffix}
              />
            )}
          </div>
        )}
        {children}
      </CardContent>
    </Card>
  );
};

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

export interface DashboardStatCardMiniSkeletonProps {
  gradient?: GradientVariant;
  hasIcon?: boolean;
  hasSubtitle?: boolean;
  className?: string;
}

export const DashboardStatCardMiniSkeleton: React.FC<
  DashboardStatCardMiniSkeletonProps
> = ({ gradient = "slate", hasIcon = true, hasSubtitle = true, className }) => {
  const gradientClass = gradient === "custom" ? "" : GRADIENT_PRESETS[gradient];

  return (
    <Card
      className={cn(
        gradientClass,
        "backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20",
        className
      )}
    >
      <CardHeader className="flex flex-row items-center justify-between space-y-0 px-4 py-3">
        <div className="h-4 w-20 bg-white/20 animate-pulse rounded" />
        {hasIcon && <div className="h-9 w-9 bg-white/20 animate-pulse rounded-full" />}
      </CardHeader>
      <CardContent className="p-4 pt-1">
        <div className="h-9 w-28 bg-white/20 animate-pulse rounded mb-2" />
        {hasSubtitle && <div className="h-4 w-24 bg-white/10 animate-pulse rounded" />}
      </CardContent>
    </Card>
  );
};

export default DashboardStatCardMini;
