"use client";
import { useState, useRef, useEffect } from "react";
import { motion, useInView, AnimatePresence } from "framer-motion";
import { Star, ThumbsUp, ChevronDown, BadgeCheck } from "lucide-react";
import { useSeller } from "@/lib/SellerContext";
import type { Review } from "./types";
import { formatProfileDate } from "./mockData";

function StarRow({ rating, size = 14 }: { rating: number; size?: number }) {
  return (
    <span className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((s) => (
        <Star
          key={s}
          size={size}
          fill={s <= Math.round(rating) ? "#f0c040" : "none"}
          color={s <= Math.round(rating) ? "#f0c040" : "rgba(255,255,255,0.2)"}
        />
      ))}
    </span>
  );
}

function RatingBar({ stars, count, total, delay }: { stars: number; count: number; total: number; delay: number }) {
  const barRef = useRef<HTMLDivElement>(null);
  const isInView = useInView(barRef, { once: true, margin: "-10px" });
  const pct = total > 0 ? (count / total) * 100 : 0;

  return (
    <div ref={barRef} className="flex items-center gap-2">
      <div className="flex items-center gap-0.5 shrink-0 w-14">
        <span className="text-xs text-[var(--text-muted)] tabular-nums">{stars}</span>
        <Star size={11} fill="#f0c040" color="#f0c040" />
      </div>
      <div className="flex-1 h-2 rounded-full overflow-hidden" style={{ background: "rgba(255,255,255,0.06)" }}>
        <motion.div
          className="h-full rounded-full"
          style={{ background: stars >= 4 ? "#22c55e" : stars === 3 ? "#f0c040" : "#f87171" }}
          initial={{ width: 0 }}
          animate={{ width: isInView ? `${pct}%` : 0 }}
          transition={{ delay, duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
        />
      </div>
      <span className="text-xs text-[var(--text-muted)] tabular-nums shrink-0 w-6 text-right">{count}</span>
    </div>
  );
}

function ReviewCard({ review, idx }: { review: Review; idx: number }) {
  const [expanded, setExpanded] = useState(false);
  const isLong = review.text.length > 150;
  const displayText = expanded || !isLong ? review.text : review.text.slice(0, 150) + "…";

  return (
    <motion.div
      initial={{ opacity: 0, y: 14 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: idx * 0.07, type: "spring", stiffness: 280, damping: 26 }}
      className="p-4 rounded-2xl"
      style={{ background: "var(--card)", border: "1px solid var(--border)" }}
    >
      {/* Buyer row */}
      <div className="flex items-start gap-3 mb-3">
        <img
          src={review.buyerAvatar}
          alt={review.buyerName}
          className="w-10 h-10 rounded-xl object-cover shrink-0"
        />
        <div className="flex-1 min-w-0">
          <div className="flex items-center flex-wrap gap-1.5 mb-0.5">
            <p className="text-sm font-bold text-[var(--text-primary)]">{review.buyerName}</p>
            {review.verified && (
              <span
                className="flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[9px] font-bold"
                style={{ background: "rgba(34,197,94,0.12)", color: "#22c55e", border: "1px solid rgba(34,197,94,0.25)" }}
              >
                <BadgeCheck size={9} />
                Verified Purchase
              </span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <StarRow rating={review.rating} size={11} />
            <span className="text-[10px] text-[var(--text-muted)]">{formatProfileDate(review.date)}</span>
          </div>
        </div>
      </div>

      {/* Product chip */}
      <div className="flex items-center gap-2 mb-3 p-2 rounded-xl" style={{ background: "rgba(255,255,255,0.03)", border: "1px solid var(--border)" }}>
        <img src={review.productImage} alt="" className="w-7 h-7 rounded-lg object-cover shrink-0" />
        <p className="text-[10px] text-[var(--text-muted)] line-clamp-1">{review.productTitle}</p>
      </div>

      {/* Review text */}
      <p className="text-sm font-bold text-[var(--text-primary)] mb-1">{review.title}</p>
      <p className="text-xs text-[var(--text-muted)] leading-relaxed mb-3">{displayText}</p>

      {isLong && (
        <button
          onClick={() => setExpanded((v) => !v)}
          className="flex items-center gap-1 text-[11px] font-semibold mb-3"
          style={{ color: "var(--accent)" }}
        >
          <ChevronDown size={12} className={expanded ? "rotate-180" : ""} style={{ transition: "transform 0.2s" }} />
          {expanded ? "Show less" : "Read more"}
        </button>
      )}

      {/* Helpful */}
      <div className="flex items-center gap-1.5 text-[10px] text-[var(--text-muted)]">
        <ThumbsUp size={11} />
        <span>{review.helpful} found this helpful</span>
      </div>
    </motion.div>
  );
}

interface Props {
  onLeaveReview: () => void;
}

export function RatingsReviews({ onLeaveReview }: Props) {
  const { profile } = useSeller();
  const { stats, ratingDistribution, reviews } = profile;
  const total = Object.values(ratingDistribution).reduce((a, b) => a + b, 0);

  const [showAll, setShowAll] = useState(false);
  const displayedReviews = showAll ? reviews : reviews.slice(0, 3);

  return (
    <div className="mb-4" id="reviews">
      {/* Rating summary */}
      <div className="px-4 mb-4">
        <div className="rounded-2xl p-4" style={{ background: "var(--card)", border: "1px solid var(--border)" }}>
          <h2 className="text-base font-bold text-[var(--text-primary)] mb-4">Ratings & Reviews</h2>
          <div className="flex gap-4 items-start">
            {/* Big rating */}
            <div className="shrink-0 text-center">
              <p className="text-5xl font-black tabular-nums" style={{ color: "#f0c040", lineHeight: 1 }}>
                {stats.averageRating.toFixed(1)}
              </p>
              <StarRow rating={stats.averageRating} size={14} />
              <p className="text-[10px] text-[var(--text-muted)] mt-1">{stats.totalReviews} reviews</p>
            </div>

            {/* Distribution bars */}
            <div className="flex-1 space-y-1.5">
              {([5, 4, 3, 2, 1] as const).map((stars, i) => (
                <RatingBar
                  key={stars}
                  stars={stars}
                  count={ratingDistribution[stars]}
                  total={total}
                  delay={i * 0.08}
                />
              ))}
            </div>
          </div>

          {/* Positive reviews */}
          <div
            className="mt-4 flex items-center justify-between p-3 rounded-xl"
            style={{ background: "rgba(34,197,94,0.06)", border: "1px solid rgba(34,197,94,0.2)" }}
          >
            <span className="text-xs text-[var(--text-muted)]">Positive review rate</span>
            <span className="text-sm font-black" style={{ color: "#22c55e" }}>
              {stats.positiveReviewsPercent}%
            </span>
          </div>
        </div>
      </div>

      {/* Leave review CTA */}
      <div className="px-4 mb-4">
        <button
          onClick={onLeaveReview}
          className="w-full flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-bold text-white transition-all active:scale-[0.98]"
          style={{ background: "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)", boxShadow: "0 4px 14px rgba(252,0,0,0.3)" }}
        >
          <Star size={15} />
          Leave a Review
        </button>
      </div>

      {/* Review cards */}
      {reviews.length === 0 ? (
        <div className="mx-4 rounded-2xl p-8 text-center" style={{ background: "var(--card)", border: "1px solid var(--border)" }}>
          <div className="text-4xl mb-3">⭐</div>
          <p className="font-semibold text-[var(--text-primary)] mb-1">No Reviews Yet</p>
          <p className="text-sm text-[var(--text-muted)]">Be the first to leave a review for this seller.</p>
        </div>
      ) : (
        <div className="px-4 space-y-3">
          <AnimatePresence>
            {displayedReviews.map((review, i) => (
              <ReviewCard key={review.id} review={review} idx={i} />
            ))}
          </AnimatePresence>

          {reviews.length > 3 && (
            <button
              onClick={() => setShowAll((v) => !v)}
              className="w-full flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-semibold transition-all"
              style={{ background: "var(--card)", color: "var(--text-muted)", border: "1px solid var(--border)" }}
            >
              <ChevronDown
                size={15}
                className={showAll ? "rotate-180" : ""}
                style={{ transition: "transform 0.25s" }}
              />
              {showAll ? "Show less" : `Show all ${reviews.length} reviews`}
            </button>
          )}
        </div>
      )}
    </div>
  );
}
