import { useEffect, useMemo, useState } from "react";
import { Star, Quote, ChevronLeft, ChevronRight } from "lucide-react";
import {
  fetchPublicTestimonials,
  type ServiceTestimonial,
} from "@/lib/testimonials";

/**
 * Customer testimonials carousel for the Service Catalog page.
 * Loads active testimonials from Atoms Cloud and auto-advances every 6s.
 */
export default function TestimonialsCarousel() {
  const [items, setItems] = useState<ServiceTestimonial[]>([]);
  const [index, setIndex] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      const rows = await fetchPublicTestimonials();
      if (!active) return;
      setItems(rows);
      setLoading(false);
    })();
    return () => {
      active = false;
    };
  }, []);

  useEffect(() => {
    if (items.length <= 1) return;
    const t = setInterval(() => {
      setIndex((i) => (i + 1) % items.length);
    }, 6000);
    return () => clearInterval(t);
  }, [items.length]);

  const current = useMemo(() => items[index], [items, index]);

  const prev = () =>
    setIndex((i) => (i - 1 + items.length) % Math.max(items.length, 1));
  const next = () => setIndex((i) => (i + 1) % Math.max(items.length, 1));

  if (loading) {
    return (
      <section className="relative bg-black text-white py-20 md:py-28 overflow-hidden">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <div className="h-8 w-56 mx-auto bg-white/5 rounded animate-pulse" />
          <div className="mt-8 h-48 bg-white/5 rounded-2xl animate-pulse" />
        </div>
      </section>
    );
  }

  if (!current) return null;

  return (
    <section className="relative bg-black text-white py-20 md:py-28 overflow-hidden">
      <div
        aria-hidden="true"
        className="absolute inset-0 bg-gradient-to-br from-[#05130a] via-black to-[#031a05]"
      />
      <div
        aria-hidden="true"
        className="absolute top-10 left-1/4 w-[500px] h-[300px] rounded-full bg-[#0e6305]/20 blur-[140px]"
      />
      <div
        aria-hidden="true"
        className="absolute bottom-10 right-1/4 w-[400px] h-[250px] rounded-full bg-[#d4af37]/10 blur-[140px]"
      />

      <div className="relative max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Heading */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#d4af37]/40 bg-[#d4af37]/5 text-[#f0d674] text-xs font-bold uppercase tracking-widest mb-4">
            <Quote className="w-3.5 h-3.5" />
            Client Stories
          </div>
          <h2 className="text-3xl md:text-5xl font-black leading-tight">
            Trusted by{" "}
            <span className="bg-gradient-to-r from-[#22c55e] to-[#d4af37] bg-clip-text text-transparent">
              Leading Businesses
            </span>
          </h2>
          <p className="text-slate-400 mt-4 max-w-2xl mx-auto">
            Real stories from organizations that rely on DoItEasy to run their
            digital infrastructure.
          </p>
        </div>

        {/* Carousel Card */}
        <div className="relative">
          <div className="bg-gradient-to-br from-white/[0.06] to-white/[0.02] border border-white/10 rounded-3xl p-8 md:p-12 backdrop-blur-sm shadow-2xl">
            <Quote
              aria-hidden="true"
              className="absolute top-6 right-6 w-20 h-20 text-[#d4af37]/10"
            />

            <div className="flex flex-col md:flex-row items-center md:items-start gap-6 md:gap-10">
              {/* Avatar / Logo */}
              <div className="shrink-0">
                <div className="w-24 h-24 md:w-28 md:h-28 rounded-2xl bg-white flex items-center justify-center overflow-hidden ring-2 ring-[#d4af37]/30 shadow-lg">
                  {current.avatar_url ? (
                    <img
                      src={current.avatar_url}
                      alt={`${current.company} logo`}
                      className="w-full h-full object-contain p-2"
                      onError={(e) => {
                        (e.currentTarget as HTMLImageElement).style.display =
                          "none";
                      }}
                    />
                  ) : (
                    <div className="w-full h-full bg-gradient-to-br from-[#0b6e3e] to-[#0a8048] flex items-center justify-center text-white text-2xl font-black">
                      {current.name.charAt(0)}
                    </div>
                  )}
                </div>
              </div>

              {/* Content */}
              <div className="flex-1 text-center md:text-left">
                {/* Rating */}
                <div className="flex items-center justify-center md:justify-start gap-1 mb-4">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <Star
                      key={i}
                      className={`w-5 h-5 ${
                        i < (current.rating ?? 0)
                          ? "fill-[#d4af37] text-[#d4af37]"
                          : "text-slate-600"
                      }`}
                    />
                  ))}
                </div>

                {/* Quote */}
                <blockquote className="text-lg md:text-xl text-slate-200 leading-relaxed font-light italic">
                  “{current.quote}”
                </blockquote>

                {/* Attribution */}
                <div className="mt-6 pt-6 border-t border-white/10">
                  <div className="font-bold text-white text-base md:text-lg">
                    {current.name}
                  </div>
                  <div className="text-sm text-slate-400">
                    {current.role ? `${current.role} · ` : ""}
                    <span className="text-[#f0d674] font-semibold">
                      {current.company}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Nav buttons */}
          {items.length > 1 && (
            <>
              <button
                type="button"
                onClick={prev}
                aria-label="Previous testimonial"
                className="absolute left-2 md:-left-5 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-white/10 hover:bg-white/20 border border-white/20 text-white flex items-center justify-center backdrop-blur transition"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
              <button
                type="button"
                onClick={next}
                aria-label="Next testimonial"
                className="absolute right-2 md:-right-5 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-white/10 hover:bg-white/20 border border-white/20 text-white flex items-center justify-center backdrop-blur transition"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </>
          )}
        </div>

        {/* Dots */}
        {items.length > 1 && (
          <div className="flex items-center justify-center gap-2 mt-8">
            {items.map((_, i) => (
              <button
                key={i}
                type="button"
                aria-label={`Go to testimonial ${i + 1}`}
                onClick={() => setIndex(i)}
                className={`h-2 rounded-full transition-all ${
                  i === index
                    ? "w-8 bg-gradient-to-r from-[#22c55e] to-[#d4af37]"
                    : "w-2 bg-white/20 hover:bg-white/40"
                }`}
              />
            ))}
          </div>
        )}
      </div>
    </section>
  );
}