import { useState, useEffect } from 'react';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Quote, ChevronLeft, ChevronRight } from 'lucide-react';
import { getNodes, normalizeDrupalUrl } from '../services/drupalAPI';

function Testimonials() {
  const [currentTestimonial, setCurrentTestimonial] = useState(0);
  const [testimonials, setTestimonials] = useState([]);
  const [facts, setFacts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getNodes(
      'testimonial',
      [{ fieldName: 'field_media_image', mode: 'media', mediaSourceField: 'field_media_image' }]
    )
      .then(setTestimonials)
      .catch(console.error)
      .finally(() => setLoading(false));
      getNodes('facts').then(setFacts).catch(console.error);
  }, []);

  useEffect(() => {
    if (!testimonials.length) return;
    const timer = setInterval(() => {
      setCurrentTestimonial((prev) => (prev + 1) % testimonials.length);
    }, 5000);
    return () => clearInterval(timer);
  }, [testimonials.length]);

  const getImageUrl = (item) => {
    if (!item) return null;
    const resolved = item.field_media_image_resolved;
    if (!resolved) return null;
    const url = Array.isArray(resolved)
      ? resolved[0]?.file?.attributes?.uri?.url
      : resolved?.file?.attributes?.uri?.url;
    return normalizeDrupalUrl(url);
  };

  const next = () => setCurrentTestimonial((prev) => (prev + 1) % testimonials.length);
  const prev = () => setCurrentTestimonial((prev) => (prev - 1 + testimonials.length) % testimonials.length);

  if (loading) return <p>Loading...</p>;
  if (!testimonials.length) return null;

  const current = testimonials[currentTestimonial];
  const imageUrl = getImageUrl(current);

  return (
    <section className="py-16 lg:py-24 bg-[#f8f9fa]">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-16">
          <h2 className="text-3xl lg:text-4xl font-bold text-[#383838] mb-4">
            What Our Patients Say
          </h2>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            Don't just take our word for it. Hear from the thousands of patients
            who have experienced life-changing results with our hearing care services.
          </p>
        </div>

        {/* Carousel */}
        <div className="relative max-w-4xl mx-auto">
          <Card className="bg-white shadow-xl shadow-[#8ac642]/10 border-0">
            <CardContent className="p-8 lg:p-12">
              <div className="flex flex-col lg:flex-row gap-8 items-center">
                {/* Image */}
                <div className="flex-shrink-0">
                  <div className="relative">
                    <div className="w-24 h-24 lg:w-32 lg:h-32 rounded-full overflow-hidden shadow-lg shadow-[#8ac642]/20 bg-gray-100">
                      {imageUrl && (
                        <img
                          src={imageUrl}
                          alt={current.attributes.title}
                          className="w-full h-full object-cover"
                          onError={(e) => { e.target.style.display = 'none'; }}
                        />
                      )}
                    </div>
                    <div className="absolute -top-2 -right-2 w-8 h-8 bg-[#8ac642] rounded-full flex items-center justify-center">
                      <Quote className="w-4 h-4 text-white" />
                    </div>
                  </div>
                </div>

                {/* Content */}
                <div className="flex-1 text-center lg:text-left space-y-4">
                  {/* Body */}
                  <div className="text-lg lg:text-xl text-[#383838] leading-relaxed italic">
                    {current.attributes.body?.processed
                      ? <div dangerouslySetInnerHTML={{ __html: `${current.attributes.body.processed}` }} />
                      : `${current.attributes.body?.value || ''}`}
                  </div>

                  {/* Name */}
                  <p className="font-semibold text-[#383838] text-lg">
                    {current.attributes.title}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Navigation */}
          <div className="flex justify-center mt-8 space-x-4">
            <Button
              variant="outline"
              size="icon"
              onClick={prev}
              className="rounded-full border-[#8ac642] text-[#8ac642] hover:bg-[#8ac642] hover:text-white"
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <Button
              variant="outline"
              size="icon"
              onClick={next}
              className="rounded-full border-[#8ac642] text-[#8ac642] hover:bg-[#8ac642] hover:text-white"
            >
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>

          {/* Dots */}
          <div className="flex justify-center mt-4 space-x-2">
            {testimonials.map((_, index) => (
              <button
                key={index}
                onClick={() => setCurrentTestimonial(index)}
                className={`h-3 rounded-full transition-all duration-300 ${
                  index === currentTestimonial
                    ? 'bg-[#8ac642] w-8'
                    : 'bg-gray-300 hover:bg-gray-400 w-3'
                }`}
              />
            ))}
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8 mt-16">
          {facts.map((fact, index) => (
            <div key={index} className="text-center">
              <div className="text-2xl lg:text-3xl font-bold text-[#8ac642] mb-2">{fact.attributes.field_text_1}{fact.attributes.field_text_2}</div>
              <div className="text-gray-600">{fact.attributes.title}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

  

export default Testimonials;