"use client";

import React, { useState, useEffect, useRef } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { getFeaturedReviewsAction } from "@/actions/reviews/reviews.action";
import type { Review } from "@/types";

// Modular Subcomponents
import ReviewCard from "./ReviewCard";
import ReviewForm from "./ReviewForm";
import ReviewDetailModal from "./ReviewDetailModal";
import LightboxModal from "./LightboxModal";

export default function ReviewsSection() {
  const [reviews, setReviews] = useState<Review[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeReview, setActiveReview] = useState<Review | null>(null);
  const [lightboxImage, setLightboxImage] = useState<string | null>(null);

  // Scroll State
  const scrollRef = useRef<HTMLDivElement>(null);
  const scrollPosRef = useRef<number>(0);
  const targetScrollPosRef = useRef<number>(0);
  const [isHovered, setIsHovered] = useState(false);

  // Load reviews on mount & expose a refresh callback
  const loadReviews = async () => {
    try {
      const res = await getFeaturedReviewsAction();
      if (res.success && res.data) {
        setReviews(res.data);
      }
    } catch (err) {
      console.error("Failed to load reviews:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadReviews();
  }, []);

  // Auto Scroll Loop
  useEffect(() => {
    const scrollContainer = scrollRef.current;
    if (!scrollContainer || loading || reviews.length === 0) return;

    let animationFrameId: number;
    let lastTime = performance.now();
    scrollPosRef.current = scrollContainer.scrollLeft;
    targetScrollPosRef.current = scrollContainer.scrollLeft;

    const step = (time: number) => {
      if (scrollContainer) {
        const delta = (time - lastTime) / 1000;

        // Pause scrolling if modal is open, or if hovered
        if (!isHovered && !activeReview) {
          const speed = 25; // Speed in pixels per second
          targetScrollPosRef.current += speed * delta;
        }

        // Interpolate current scroll position towards the target (lerp)
        const diff = targetScrollPosRef.current - scrollPosRef.current;
        scrollPosRef.current += diff * 0.1; // damping speed

        // Loop boundaries
        const maxScroll = scrollContainer.scrollWidth - scrollContainer.clientWidth;
        if (targetScrollPosRef.current >= maxScroll - 1) {
          targetScrollPosRef.current = 0;
          scrollPosRef.current = 0;
        } else if (targetScrollPosRef.current < 0) {
          targetScrollPosRef.current = 0;
          scrollPosRef.current = 0;
        }

        scrollContainer.style.scrollBehavior = "auto";
        scrollContainer.scrollLeft = Math.round(scrollPosRef.current);
      }
      lastTime = time;
      animationFrameId = requestAnimationFrame(step);
    };

    animationFrameId = requestAnimationFrame(step);

    return () => {
      cancelAnimationFrame(animationFrameId);
    };
  }, [isHovered, activeReview, loading, reviews]);

  // Button scroll handlers
  const scrollPrev = () => {
    if (!scrollRef.current) return;
    targetScrollPosRef.current -= 380;
  };

  const scrollNext = () => {
    if (!scrollRef.current) return;
    targetScrollPosRef.current += 380;
  };

  const repeatedReviews = reviews.length > 0 ? Array(Math.ceil(12 / reviews.length)).fill(reviews).flat() : [];

  return (
    <section id="reviews" className="py-20 bg-[#faf7f3] border-t border-zinc-200/50 relative overflow-hidden">
      {/* Header */}
      <div className="max-w-6xl mx-auto px-6 mb-16 text-center">
        <span className="text-xs uppercase tracking-widest font-black text-brand-accent mb-3 block">
          Customer Love
        </span>
        <h2 className="text-3xl md:text-5xl font-black text-zinc-900 uppercase tracking-tight mb-4">
          What People Are Saying
        </h2>
        <p className="text-zinc-650 text-sm md:text-base font-medium max-w-lg mx-auto">
          Real feedback from verified buyers of our electronics and appliances.
        </p>
      </div>

      {/* Manual Drag / Scroll Carousel */}
      {loading ? (
        <div className="w-full bg-zinc-100/40 border-y border-zinc-200/40 py-8 select-none mb-20 relative">
          <div className="absolute left-0 top-0 bottom-0 w-24 bg-gradient-to-r from-[#faf7f3] to-transparent z-10 pointer-events-none" />
          <div className="absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-[#faf7f3] to-transparent z-10 pointer-events-none" />

          <div className="flex gap-6 overflow-x-auto scrollbar-none py-2 px-8 md:px-24 select-none">
            {[...Array(10)].map((_, idx) => (
              <div
                key={idx}
                className="flex-shrink-0 w-[300px] md:w-[360px] bg-white border border-zinc-200/80 rounded-2xl p-6 flex flex-col justify-between h-[180px]"
              >
                <div>
                  {/* Rating Stars Skeleton */}
                  <div className="flex gap-1 mb-3">
                    {[...Array(5)].map((_, i) => (
                      <div
                        key={i}
                        className="w-3.5 h-3.5 bg-slate-100 rounded-full animate-pulse"
                      />
                    ))}
                  </div>
                  {/* Content Skeleton */}
                  <div className="h-3 bg-slate-100 rounded w-full mb-2 animate-pulse" />
                  <div className="h-3 bg-slate-100 rounded w-5/6 mb-2 animate-pulse" />
                  <div className="h-3 bg-slate-100 rounded w-2/3 animate-pulse" />
                </div>
                {/* Meta Skeleton */}
                <div className="flex items-center justify-between mt-auto">
                  <div className="space-y-1">
                    <div className="h-3 bg-slate-200 rounded w-24 animate-pulse" />
                    <span className="text-[10px] text-zinc-550 font-semibold uppercase tracking-wider block">
                      Verified Buyer
                    </span>
                  </div>
                  <div className="w-12 h-12 bg-slate-100 border border-slate-100 rounded-xl animate-pulse" />
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : reviews.length > 0 ? (
        <div className="w-full bg-zinc-100/40 border-y border-zinc-200/40 py-8 select-none mb-20 relative">
          {/* Edge Fades */}
          <div className="absolute left-0 top-0 bottom-0 w-24 bg-gradient-to-r from-[#faf7f3] to-transparent z-10 pointer-events-none" />
          <div className="absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-[#faf7f3] to-transparent z-10 pointer-events-none" />

          {/* Draggable container */}
          <div
            ref={scrollRef}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            className="flex gap-6 overflow-x-hidden scrollbar-none py-2 px-8 md:px-24 select-none"
          >
            {repeatedReviews.map((review, idx) => (
              <ReviewCard
                key={`${review.id}-${idx}`}
                review={review}
                onClick={() => {
                  setActiveReview(review);
                }}
              />
            ))}
          </div>

          {/* Navigation Controls */}
          <div className="flex items-center justify-center gap-4 mt-6">
            <button
              onClick={scrollPrev}
              className="w-10 h-10 rounded-full border border-zinc-200 bg-white flex items-center justify-center text-zinc-650 hover:bg-zinc-50 hover:text-brand-accent transition-all active:scale-95 shadow-sm cursor-pointer"
              aria-label="Previous reviews"
            >
              <ChevronLeft size={20} />
            </button>
            <button
              onClick={scrollNext}
              className="w-10 h-10 rounded-full border border-zinc-200 bg-white flex items-center justify-center text-zinc-650 hover:bg-zinc-50 hover:text-brand-accent transition-all active:scale-95 shadow-sm cursor-pointer"
              aria-label="Next reviews"
            >
              <ChevronRight size={20} />
            </button>
          </div>
        </div>
      ) : null}

      {/* Submission Form Section */}
      <div className="container mx-auto px-4 lg:px-6 relative z-10">
        <ReviewForm onSuccess={loadReviews} />
      </div>

      {/* Modal Level 1: Review details */}
      {activeReview && (
        <ReviewDetailModal
          review={activeReview}
          onClose={() => setActiveReview(null)}
          onZoomImage={(imgUrl) => setLightboxImage(imgUrl)}
        />
      )}

      {/* Modal Level 2: Full photo lightbox */}
      {lightboxImage && (
        <LightboxModal imageUrl={lightboxImage} onClose={() => setLightboxImage(null)} />
      )}
    </section>
  );
}
