"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { Card } from "@/components/ui/card";

export type TrendDirection = "up" | "down" | "neutral";

export interface SparklinePoint {
  value: number;
}

export interface MetricCardProps extends React.HTMLAttributes<HTMLDivElement> {
  /** 小号大写字母标签（如 "TOTAL JOBS TODAY"） */
  label: string;
  /** 主数字/值 */
  value: string | number;
  /** 次要描述，显示在主值下方 */
  subValue?: string;
  /** 趋势方向 */
  trend?: TrendDirection;
  /** 趋势百分比，如 "+18%" */
  trendValue?: string;
  /** 趋势说明文字，如 "vs last month" */
  trendLabel?: string;
  /** sparkline 数据点 */
  sparklineData?: SparklinePoint[];
  /** 图标（可选的左侧小图标） */
  icon?: React.ReactNode;
  /** 卡片尺寸 */
  size?: "sm" | "default" | "lg";
}

const TrendArrow = ({ direction }: { direction: TrendDirection }) => {
  if (direction === "neutral") return null;
  const isUp = direction === "up";
  return (
    <svg
      className={cn("h-3.5 w-3.5", isUp ? "text-primary" : "text-destructive")}
      viewBox="0 0 14 14"
      fill="none"
    >
      {isUp ? (
        <path d="M7 11V3M7 3L3.5 6.5M7 3L10.5 6.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      ) : (
        <path d="M7 3V11M7 11L3.5 7.5M7 11L10.5 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      )}
    </svg>
  );
};

const Sparkline = ({ data, trend }: { data: SparklinePoint[]; trend?: TrendDirection }) => {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data.map((d) => d.value));
  const min = Math.min(...data.map((d) => d.value));
  const range = max - min || 1;
  const width = 80;
  const height = 28;
  const points = data.map((d, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((d.value - min) / range) * height;
    return `${x},${y}`;
  });
  const isUp = trend !== "down";
  return (
    <svg width={width} height={height} className="overflow-visible">
      <polyline
        points={points.join(" ")}
        fill="none"
        stroke={isUp ? "currentColor" : "#ef4444"}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={isUp ? "text-primary" : "text-destructive"}
      />
      {/* last dot */}
      <circle
        cx={parseFloat(points[points.length - 1].split(",")[0])}
        cy={parseFloat(points[points.length - 1].split(",")[1])}
        r="2.5"
        fill={isUp ? "#10B981" : "#ef4444"}
      />
    </svg>
  );
};

const MetricCard = React.forwardRef<HTMLDivElement, MetricCardProps>(
  (
    {
      className,
      label,
      value,
      subValue,
      trend = "neutral",
      trendValue,
      trendLabel,
      sparklineData,
      icon,
      size = "default",
      ...props
    },
    ref
  ) => {
    const paddingClass = {
      sm: "p-4",
      default: "p-5",
      lg: "p-6",
    }[size];

    const valueClass = {
      sm: "text-2xl",
      default: "text-3xl",
      lg: "text-4xl",
    }[size];

    return (
      <Card
        ref={ref}
        className={cn("group relative overflow-hidden", className)}
        {...props}
      >
        <div className={cn("flex flex-col gap-2", paddingClass)}>
          {/* Label row */}
          <div className="flex items-center justify-between">
            <p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
              {label}
            </p>
            {icon && (
              <div className="flex h-7 w-7 items-center justify-center rounded-md bg-primary/10 text-primary">
                {icon}
              </div>
            )}
          </div>

          {/* Value + sparkline row */}
          <div className="flex items-end justify-between gap-2">
            <div className="flex flex-col gap-1">
              <span
                className={cn(
                  "font-bold tracking-tight text-foreground leading-none",
                  valueClass
                )}
                style={{ fontVariantNumeric: "tabular-nums" }}
              >
                {value}
              </span>
              {subValue && (
                <span className="text-xs text-muted-foreground">{subValue}</span>
              )}
            </div>
            {sparklineData && sparklineData.length >= 2 && (
              <div className="mb-0.5 opacity-80 group-hover:opacity-100 transition-opacity">
                <Sparkline data={sparklineData} trend={trend} />
              </div>
            )}
          </div>

          {/* Trend row */}
          {(trendValue || trendLabel) && (
            <div className="flex items-center gap-1.5">
              {trendValue && (
                <div
                  className={cn(
                    "flex items-center gap-0.5 text-xs font-semibold",
                    trend === "up" && "text-primary",
                    trend === "down" && "text-destructive",
                    trend === "neutral" && "text-muted-foreground"
                  )}
                >
                  <TrendArrow direction={trend} />
                  <span>{trendValue}</span>
                </div>
              )}
              {trendLabel && (
                <span className="text-xs text-muted-foreground">{trendLabel}</span>
              )}
            </div>
          )}
        </div>

        {/* subtle background accent */}
        <div
          className={cn(
            "pointer-events-none absolute bottom-0 right-0 h-16 w-16 rounded-tl-3xl opacity-5 transition-opacity duration-300 group-hover:opacity-10",
            trend === "up" && "bg-primary",
            trend === "down" && "bg-destructive",
            trend === "neutral" && "bg-muted-foreground"
          )}
        />
      </Card>
    );
  }
);
MetricCard.displayName = "MetricCard";

export { MetricCard };
