"use client";
import { useRef, useEffect, useState } from "react";
import { motion, useInView, animate } from "framer-motion";
import { Shield, Star, CheckCircle, MessageCircle, AlertTriangle } from "lucide-react";
import { useSeller } from "@/lib/SellerContext";
import { getTrustScoreColor, getTrustScoreLabel } from "./mockData";

interface FactorBarProps {
  label: string;
  value: number;
  color: string;
  delay: number;
  icon: React.ReactNode;
}

function FactorBar({ label, value, color, delay, icon }: FactorBarProps) {
  const ref = useRef<HTMLDivElement>(null);
  const isInView = useInView(ref, { once: true, margin: "-10px" });

  return (
    <div ref={ref} className="flex items-center gap-3">
      <div
        className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0"
        style={{ background: `${color}18` }}
      >
        {icon}
      </div>
      <div className="flex-1">
        <div className="flex items-center justify-between mb-1">
          <span className="text-xs text-[var(--text-muted)]">{label}</span>
          <span className="text-xs font-bold" style={{ color }}>{value}%</span>
        </div>
        <div className="h-1.5 rounded-full overflow-hidden" style={{ background: "rgba(255,255,255,0.06)" }}>
          <motion.div
            className="h-full rounded-full"
            style={{ background: color }}
            initial={{ width: 0 }}
            animate={{ width: isInView ? `${value}%` : 0 }}
            transition={{ delay, duration: 0.9, ease: [0.16, 1, 0.3, 1] }}
          />
        </div>
      </div>
    </div>
  );
}

function TrustGauge({ score }: { score: number }) {
  const [progress, setProgress] = useState(0);
  const gaugeRef = useRef<SVGPathElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const isInView = useInView(containerRef, { once: true });

  const radius = 78;
  const circumference = Math.PI * radius;

  useEffect(() => {
    if (!isInView) return;
    const controls = animate(0, score, {
      duration: 1.6,
      ease: [0.16, 1, 0.3, 1],
      onUpdate: (v) => setProgress(v),
    });
    return controls.stop;
  }, [isInView, score]);

  const dashOffset = circumference - (progress / 100) * circumference;
  const color = getTrustScoreColor(score);

  return (
    <div ref={containerRef} className="flex flex-col items-center">
      <div className="relative">
        <svg width="200" height="115" viewBox="0 0 200 115" className="overflow-visible">
          {/* Background track */}
          <path
            d="M 22 100 A 78 78 0 0 1 178 100"
            stroke="rgba(255,255,255,0.07)"
            strokeWidth="14"
            strokeLinecap="round"
            fill="none"
          />
          {/* Progress arc */}
          <path
            d="M 22 100 A 78 78 0 0 1 178 100"
            stroke={color}
            strokeWidth="14"
            strokeLinecap="round"
            fill="none"
            strokeDasharray={circumference}
            strokeDashoffset={dashOffset}
            style={{ filter: `drop-shadow(0 0 8px ${color}60)` }}
          />
          {/* Score number */}
          <text x="100" y="86" textAnchor="middle" fill="white" fontSize="30" fontWeight="900" fontFamily="inherit">
            {Math.round(progress)}
          </text>
          <text x="100" y="104" textAnchor="middle" fill="rgba(160,160,160,0.8)" fontSize="10" fontFamily="inherit">
            Trust Score
          </text>
        </svg>

        {/* Label badges */}
        <div className="absolute left-0 bottom-0 text-[9px] text-[var(--text-muted)] font-medium">0</div>
        <div className="absolute right-0 bottom-0 text-[9px] text-[var(--text-muted)] font-medium">100</div>
      </div>

      <div
        className="mt-2 px-4 py-1.5 rounded-full text-xs font-bold"
        style={{
          background: `${color}15`,
          color,
          border: `1px solid ${color}40`,
        }}
      >
        {getTrustScoreLabel(score)}
      </div>
    </div>
  );
}

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

  const factors: FactorBarProps[] = [
    {
      label: "Average Rating",
      value: Math.round((stats.averageRating / 5) * 100),
      color: "#f0c040",
      delay: 0.1,
      icon: <Star size={13} color="#f0c040" />,
    },
    {
      label: "Completed Orders",
      value: Math.min(100, Math.round((stats.completedOrders / 500) * 100)),
      color: "#22c55e",
      delay: 0.2,
      icon: <CheckCircle size={13} color="#22c55e" />,
    },
    {
      label: "Response Rate",
      value: stats.responseRate,
      color: "#60a5fa",
      delay: 0.3,
      icon: <MessageCircle size={13} color="#60a5fa" />,
    },
    {
      label: "Verified Status",
      value: Math.round((profile.verifications.filter((v) => v.status === "verified").length / profile.verifications.length) * 100),
      color: "#f0c040",
      delay: 0.4,
      icon: <Shield size={13} color="#f0c040" />,
    },
    {
      label: "Low Dispute Rate",
      value: 97,
      color: "#34d399",
      delay: 0.5,
      icon: <AlertTriangle size={13} color="#34d399" />,
    },
  ];

  return (
    <div className="mx-4 mb-4 rounded-2xl p-5" id="trust" style={{ background: "var(--card)", border: "1px solid var(--border)" }}>
      <h2 className="text-base font-bold text-[var(--text-primary)] mb-4">Reputation Score</h2>

      {/* Gauge */}
      <TrustGauge score={profile.trustScore} />

      {/* Divider */}
      <div className="my-5 border-t border-[var(--border)]" />

      {/* Factors */}
      <p className="text-xs font-semibold text-[var(--text-muted)] mb-3">Score Breakdown</p>
      <div className="space-y-4">
        {factors.map((f) => (
          <FactorBar key={f.label} {...f} />
        ))}
      </div>
    </div>
  );
}
