import { Button } from "@/components/ui/button";
import { useReviews } from "@/hooks/queries/useReviews";
import Autoplay from "embla-carousel-autoplay";
import useEmblaCarousel from "embla-carousel-react";
import { motion } from "framer-motion";
import { ChevronLeft, ChevronRight, Quote, Star } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import PremiumBadge from "../shared/PremiumBadge";

export default function TestimonialsSection() {
  const { data: reveiwsData } = useReviews();

  const testimonials = reveiwsData?.data.data;

  const getStars = (rating: unknown) => {
    const n = Number(rating);
    if (!Number.isFinite(n) || n <= 0) return 0;
    return Math.floor(n);
  };
  const [emblaRef, emblaApi] = useEmblaCarousel(
    { loop: true, align: "center" },
    [Autoplay({ delay: 5000, stopOnInteraction: false })],
  );
  const [selectedIndex, setSelectedIndex] = useState(0);

  const scrollPrev = useCallback(() => emblaApi?.scrollPrev(), [emblaApi]);
  const scrollNext = useCallback(() => emblaApi?.scrollNext(), [emblaApi]);

  const onSelect = useCallback(() => {
    if (!emblaApi) return;
    setSelectedIndex(emblaApi.selectedScrollSnap());
  }, [emblaApi]);

  useEffect(() => {
    if (!emblaApi) return;
    onSelect();
    emblaApi.on("select", onSelect);
    return () => {
      emblaApi.off("select", onSelect);
    };
  }, [emblaApi, onSelect]);

  return (
    <section id="testimonials" className="py-24 relative overflow-hidden">
      <div className="container mx-auto px-4 relative z-10">
        {/* Section Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
          className="text-center mb-16"
        >
          <PremiumBadge text=" Client Stories" />
          <h2 className="text-4xl md:text-5xl font-bold mb-6">
            What Our{" "}
            <span className="text-transparent bg-clip-text bg-gradient-to-r from-primary to-accent-foreground">
              Clients Say
            </span>
          </h2>
          <p className="text-muted-foreground max-w-2xl mx-auto text-lg">
            Don't just take our word for it - hear from the amazing companies
            we've had the pleasure of working with.
          </p>
        </motion.div>

        {/* Carousel */}
        <div className="relative max-w-5xl mx-auto">
          {/* Navigation Buttons */}
          <Button
            variant="outline"
            size="icon"
            onClick={scrollPrev}
            className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 z-10 rounded-full glass neon-glow hidden md:flex"
          >
            <ChevronLeft className="w-5 h-5" />
          </Button>
          <Button
            variant="outline"
            size="icon"
            onClick={scrollNext}
            className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 z-10 rounded-full glass neon-glow hidden md:flex"
          >
            <ChevronRight className="w-5 h-5" />
          </Button>

          {/* Carousel Container */}
          <div className="overflow-hidden" ref={emblaRef}>
            <div className="flex">
              {testimonials?.map((testimonial, index) => (
                <div
                  key={testimonial._id}
                  className="flex-[0_0_100%] min-w-0 px-4 md:flex-[0_0_80%] lg:flex-[0_0_60%]"
                >
                  <motion.div
                    initial={{ opacity: 0, scale: 0.9 }}
                    animate={{
                      opacity: selectedIndex === index ? 1 : 0.5,
                      scale: selectedIndex === index ? 1 : 0.9,
                    }}
                    transition={{ duration: 0.4 }}
                    className="glass-strong rounded-3xl p-8 md:p-10 relative overflow-hidden border dark:border-none"
                  >
                    {/* Triangular Quote Corner Tab */}
                    <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-bl from-primary/10 to-transparent flex items-start justify-end p-3 rounded-bl-[60px] border-l border-b border-primary/20 pointer-events-none">
                      <div className="pointer-events-auto flex items-center justify-center neon-glow w-9 h-9 rounded-full bg-primary shadow-lg">
                        <Quote className="w-4 h-4 text-primary-foreground" />
                      </div>
                    </div>

                    {/* Stars */}
                    <div className="flex gap-1 mb-6">
                      {[...Array(getStars(testimonial.rating))]?.map((_, i) => (
                        <Star
                          key={i}
                          className="w-5 h-5 fill-primary text-primary"
                        />
                      ))}
                    </div>

                    {/* review */}
                    <p className="text-lg md:text-xl text-foreground/90 mb-8 leading-relaxed">
                      "{testimonial.review}"
                    </p>

                    {/* Author */}
                    <div className="flex items-center gap-4">
                      <img
                        src={testimonial.thumbnail}
                        alt={testimonial.client_name}
                        className="w-14 h-14 rounded-full object-cover border-2 border-primary/50"
                      />
                      <div>
                        <h4 className="font-bold text-foreground">
                          {testimonial.client_name}
                        </h4>
                        <p className="text-sm text-muted-foreground">
                          {testimonial.designation}
                        </p>
                      </div>
                    </div>
                  </motion.div>
                </div>
              ))}
            </div>
          </div>

          {/* Dots Indicator */}
          <div className="flex justify-center gap-2 mt-8">
            {testimonials?.map((_, index) => (
              <button
                key={index}
                onClick={() => (emblaApi) => emblaApi?.scrollTo(index)}
                className={`w-2 h-2 rounded-full transition-all duration-300 ${
                  selectedIndex === index
                    ? "w-8 bg-primary neon-glow"
                    : "bg-muted-foreground/30 hover:bg-muted-foreground/50"
                }`}
                aria-label={`Go to slide ${index + 1}`}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
