"use client";
import { useRef, useEffect } from "react";
import { motion, useInView, animate } from "framer-motion";
import {
  Package, TrendingUp, Users, CheckCircle, Star, ThumbsUp, MessageCircle, Calendar,
  type LucideProps,
} from "lucide-react";
import { useSeller } from "@/lib/SellerContext";

type LucideIcon = React.ForwardRefExoticComponent<Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>>;

interface StatCardProps {
  icon: LucideIcon;
  label: string;
  value: number;
  suffix?: string;
  color: string;
  delay: number;
  decimal?: boolean;
}

function StatCard({ icon: Icon, label, value, suffix = "", color, delay, decimal = false }: StatCardProps) {
  const cardRef = useRef<HTMLDivElement>(null);
  const numRef = useRef<HTMLSpanElement>(null);
  const isInView = useInView(cardRef, { once: true, margin: "-20px" });

  useEffect(() => {
    if (!isInView || !numRef.current) return;
    const controls = animate(0, value, {
      duration: 1.6,
      ease: [0.16, 1, 0.3, 1],
      onUpdate: (v) => {
        if (numRef.current) {
          numRef.current.textContent = decimal ? v.toFixed(1) : Math.round(v).toString();
        }
      },
    });
    return controls.stop;
  }, [isInView, value, decimal]);

  return (
    <motion.div
      ref={cardRef}
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, type: "spring", stiffness: 280, damping: 26 }}
      className="min-w-[130px] flex-shrink-0 rounded-2xl p-4 flex flex-col gap-3"
      style={{ background: "var(--card)", border: "1px solid var(--border)" }}
    >
      <div
        className="w-10 h-10 rounded-xl flex items-center justify-center"
        style={{ background: `${color}18` }}
      >
        <Icon size={18} color={color} />
      </div>
      <div>
        <div className="flex items-baseline gap-0.5">
          <span
            ref={numRef}
            className="text-2xl font-black tabular-nums"
            style={{ color: "var(--text-primary)" }}
          >
            0
          </span>
          {suffix && (
            <span className="text-base font-bold" style={{ color }}>
              {suffix}
            </span>
          )}
        </div>
        <p className="text-xs text-[var(--text-muted)] mt-0.5 leading-tight">{label}</p>
      </div>
    </motion.div>
  );
}

export function SellerStats() {
  const { profile } = useSeller();
  const { stats } = profile;

  const items: StatCardProps[] = [
    { icon: Package, label: "Active Listings", value: stats.activeListings, color: "#60a5fa", delay: 0 },
    { icon: TrendingUp, label: "Products Sold", value: stats.productsSold, color: "#22c55e", delay: 0.06 },
    { icon: Users, label: "Followers", value: stats.followers, color: "#a78bfa", delay: 0.12 },
    { icon: CheckCircle, label: "Completed Orders", value: stats.completedOrders, color: "#34d399", delay: 0.18 },
    { icon: Star, label: "Average Rating", value: stats.averageRating, color: "#f0c040", delay: 0.24, decimal: true },
    { icon: ThumbsUp, label: "Positive Reviews", value: stats.positiveReviewsPercent, suffix: "%", color: "#fb923c", delay: 0.3 },
    { icon: MessageCircle, label: "Response Rate", value: stats.responseRate, suffix: "%", color: "#f472b6", delay: 0.36 },
    { icon: Calendar, label: "Years Active", value: stats.yearsOnMarketplace, color: "#22d3ee", delay: 0.42 },
  ];

  return (
    <div className="px-4 pb-6" id="stats">
      <h2 className="text-base font-bold text-[var(--text-primary)] mb-3">Store Statistics</h2>
      <div className="flex gap-3 overflow-x-auto pb-2 no-scrollbar">
        {items.map((item) => (
          <StatCard key={item.label} {...item} />
        ))}
      </div>
    </div>
  );
}
