"use client";
import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { formatReviewsForHome } from "@/lib/reviewUtils";

export default function TestimonialSlider() {
  const [current, setCurrent] = useState(0);
  const [animating, setAnimating] = useState(false);
  const [reviews, setReviews] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    async function loadReviews() {
      try {
        const res = await fetch("/api/reviews");
        const data = await res.json().catch(() => ({}));
        const reviews = Array.isArray(data.reviews) ? data.reviews : [];
        setReviews(formatReviewsForHome(reviews));
      } catch (error) {
        console.error("Reviews fetch failed:", error);
      } finally {
        setLoading(false);
      }
    }
    loadReviews();
  }, []);

  const displayReviews = reviews;

  const goTo = useCallback(
    (index: number) => {
      if (animating || displayReviews.length === 0) return;
      setAnimating(true);
      setExpanded(false); // Reset expanded on slide change
      setTimeout(() => {
        setCurrent(index);
        setAnimating(false);
      }, 300);
    },
    [animating, displayReviews.length]
  );

  const prev = () => goTo((current - 1 + displayReviews.length) % displayReviews.length);
  const next = useCallback(() => goTo((current + 1) % displayReviews.length), [current, displayReviews.length, goTo]);

  // Auto-slider logic
  useEffect(() => {
    if (expanded) return; // Pause if user is reading a long review
    const timer = setInterval(next, 5000);
    return () => clearInterval(timer);
  }, [next, expanded]);

  if (loading) {
    return <div className="py-20 text-[#bc9e65] text-sm animate-pulse">Loading Google reviews...</div>;
  }

  if (!displayReviews.length) {
    return <div className="py-20 text-[#bc9e65] text-sm">No reviews available at this time.</div>;
  }

  const review = displayReviews[current % displayReviews.length];
  const maxChars = 150;
  const isLong = review.text.length > maxChars;
  const displayText = expanded ? review.text : (isLong ? `${review.text.substring(0, maxChars)}...` : review.text);

  return (
    <div className="w-full max-w-3xl mx-auto relative group">
      <AnimatePresence mode="wait">
        <motion.div
          key={current}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -20 }}
          transition={{ duration: 0.3 }}
          className="bg-white/40 border border-[#bc9e65]/30 p-8 sm:p-12 shadow-sm rounded-xl relative"
        >
          {/* Quote Icon */}
          <svg className="absolute w-10 h-10 text-[#bc9e65]/20 top-6 left-6" fill="currentColor" viewBox="0 0 24 24">
            <path d="M14.017 21v-7.391c0-5.704 3.731-9.57 8.983-10.609l.995 2.151c-2.432.917-3.995 3.638-3.995 5.849h4v10h-9.983zm-14.017 0v-7.391c0-5.704 3.748-9.57 9-10.609l.996 2.151c-2.433.917-3.996 3.638-3.996 5.849h3.983v10h-9.983z" />
          </svg>

          {/* Stars */}
          <div className="flex justify-center gap-1 mb-6 text-[#bc9e65]">
            {[...Array(review.rating)].map((_, i) => (
              <svg key={i} className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
              </svg>
            ))}
          </div>

          <p className="font-sans text-[#4a3c28] text-base sm:text-lg leading-relaxed italic mb-4 min-h-[100px]">
            "{displayText}"
            {isLong && (
              <button
                onClick={() => setExpanded(!expanded)}
                className="ml-2 text-[#bc9e65] hover:text-[#8a6c3a] font-bold text-xs uppercase tracking-wider transition-colors inline-block"
              >
                {expanded ? "Read Less" : "Read More"}
              </button>
            )}
          </p>

          <div className="w-8 h-px bg-[#bc9e65]/50 mx-auto mb-4" />
          <h4 className="font-serif text-[#1a3a25] tracking-widest uppercase text-sm font-bold">
            {review.name}
          </h4>
          <span className="text-[10px] uppercase tracking-widest text-[#8a6c3a] mt-1 block">
            {review.role}
          </span>
        </motion.div>
      </AnimatePresence>

      {/* Navigation Controls */}
      <div className="flex items-center justify-center gap-6 mt-8">
        <button onClick={prev} className="p-2 text-[#8a6c3a] hover:text-[#1a3a25] transition-colors">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
        </button>
        <div className="flex items-center gap-2">
          {displayReviews.map((_, i) => (
            <button
              key={i}
              onClick={() => goTo(i)}
              className={`w-2 h-2 rounded-full transition-all duration-300 ${i === current ? 'bg-[#1a3a25] w-6' : 'bg-[#bc9e65]/40 hover:bg-[#bc9e65]'}`}
            />
          ))}
        </div>
        <button onClick={next} className="p-2 text-[#8a6c3a] hover:text-[#1a3a25] transition-colors">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><polyline points="9 18 15 12 9 6"></polyline></svg>
        </button>
      </div>
    </div>
  );
}
