"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(() => ({}));
        
        if (!res.ok) {
          const errorMessage = data?.error || `${res.status} ${res.statusText}`;
          console.warn('Reviews API returned non-ok response:', errorMessage);
        }

        if (data.error) {
          console.warn('Reviews API returned an error payload:', data.error);
        }

        // Ignore fallback reviews to show Google reviews only
        const reviews = Array.isArray(data.reviews) && !data.fallback ? data.reviews : [];
        setReviews(formatReviewsForHome(reviews));
      } catch (error) {
        console.error("Reviews fetch failed:", error);
        setReviews([]);
      } 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 Google reviews are available right now.</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-4xl mx-auto relative group">
      <AnimatePresence mode="wait">
        <motion.div
          key={current}
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.95 }}
          transition={{ duration: 0.4 }}
          className="relative bg-[#fcf9f2] p-6 sm:p-14 rounded-2xl shadow-[0_10px_40px_rgba(0,0,0,0.08)] mx-1 sm:mx-12 mt-12 border border-[#bc9e65]/20"
        >
          {/* Inner decorative border */}
          <div className="absolute inset-2 border border-[#bc9e65]/40 rounded-xl pointer-events-none" />
          
          {/* Decorative Corner accents */}
          <div className="absolute top-2 left-2 w-4 h-4 border-t border-l border-[#bc9e65] rounded-tl-lg" />
          <div className="absolute top-2 right-2 w-4 h-4 border-t border-r border-[#bc9e65] rounded-tr-lg" />
          <div className="absolute bottom-2 left-2 w-4 h-4 border-b border-l border-[#bc9e65] rounded-bl-lg" />
          <div className="absolute bottom-2 right-2 w-4 h-4 border-b border-r border-[#bc9e65] rounded-br-lg" />

          {/* Crown Crest Top Center */}
          <div className="absolute -top-10 left-1/2 -translate-x-1/2 w-20 h-20 bg-gradient-to-br from-[#fcf9f2] to-[#f5e9d0] rounded-full border border-[#bc9e65] flex items-center justify-center shadow-md z-10">
            <div className="absolute inset-1 border border-[#bc9e65]/40 rounded-full" />
            <svg className="w-8 h-8 text-[#bc9e65]" viewBox="0 0 24 24" fill="currentColor">
              <path d="M5 16L3 5l5.5 5L12 4l3.5 6L21 5l-2 11H5zm14 3c0 .6-.4 1-1 1H6c-.6 0-1-.4-1-1v-1h14v1z" />
            </svg>
          </div>

          {/* Left Quote */}
          <div className="absolute top-16 left-6 sm:left-12 text-[#bc9e65] opacity-90">
            <span className="font-serif text-6xl leading-none">“</span>
          </div>

          {/* Right Quote */}
          <div className="absolute bottom-24 right-6 sm:right-12 text-[#bc9e65] opacity-90">
            <span className="font-serif text-6xl leading-none">”</span>
          </div>

          <div className="relative z-10 px-8 sm:px-20 flex flex-col items-center text-center mt-2">
            {/* Stars */}
            <div className="flex justify-center gap-1.5 mb-4 text-[#bc9e65]">
              {[...Array(review.rating || 5)].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>

            {/* Small divider under stars */}
            <div className="flex items-center gap-2 mb-8">
               <div className="w-6 h-px bg-[#bc9e65]/50" />
               <div className="w-1.5 h-1.5 rotate-45 bg-[#bc9e65]" />
               <div className="w-6 h-px bg-[#bc9e65]/50" />
            </div>

            <p className="font-sans text-[#4a3c28] text-base sm:text-lg leading-relaxed italic mb-10 min-h-[80px]">
              "{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-32 h-px bg-gradient-to-r from-transparent via-[#bc9e65] to-transparent mb-4" />
            <h4 className="font-serif text-[#1a3a25] tracking-widest uppercase text-base font-bold">
              {review.name}
            </h4>
            <span className="text-[10px] uppercase tracking-widest text-[#8a6c3a] mt-1 block">
              {review.role || "REGULAR CUSTOMER"}
            </span>
          </div>

          {/* Bottom Lotus Ornament */}
          {/* <div className="absolute -bottom-4 left-1/2 -translate-x-1/2 bg-[#fcf9f2] px-3 z-10">
             <svg className="w-6 h-6 text-[#bc9e65]" viewBox="0 0 30 20" fill="currentColor">
               <path d="M 15,3 C 13,8 14,14 15,16 C 16,14 17,8 15,3 Z" />
             </svg>
          </div> */}
        </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>
  );
}
