'use client';
import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import styles from './ReviewsSection.module.css';
import { formatReviewsForHome } from '@/lib/reviewUtils';

export default function ReviewsSection() {
  const [current, setCurrent] = useState(0);
  const [animating, setAnimating] = useState(false);
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);

  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);
        }

        const reviews = Array.isArray(data.reviews) ? data.reviews : [];
        const formatted = formatReviewsForHome(reviews);
        setReviews(formatted);
      } catch (error) {
        console.error('Reviews fetch failed:', error);
        setReviews([]);
      } finally {
        setLoading(false);
      }
    }

    loadReviews();
  }, []);

  const displayReviews = reviews;

  const goTo = useCallback(
    (index) => {
      if (animating) return;
      setAnimating(true);
      setTimeout(() => {
        setCurrent(index);
        setAnimating(false);
      }, 300);
    },
    [animating]
  );

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

  useEffect(() => {
    const timer = setInterval(next, 5000);
    return () => clearInterval(timer);
  }, [next]);

  const review = displayReviews.length ? displayReviews[current % displayReviews.length] : null;

  return (
    <section className={styles.section}>
      <div className={styles.container}>
        <div className={styles.contentWrap}>

          <div className={styles.imageCol}>
            <div className={styles.collage}>
              <div className={styles.imgLeft}>
                <Image src="/images/story-heritage.png" alt="Dosa" fill className={styles.img} />
              </div>
              <div className={styles.imgRight}>
                <Image src="/images/sambar.png" alt="Sambar" fill className={styles.img} />
              </div>
              <div className={styles.ratingBadge}>
                <span className={styles.ratingText}>My Dosa <br /> Place</span>
              </div>
            </div>
          </div>

          <div className={styles.textCol}>
            <span className={styles.eyebrow}>
              <span className={styles.eyebrowIcon}>💬</span> Google Reviews
            </span>
            <h2 className={styles.sectionTitle}>
              What Our Customers <em>Say</em>
            </h2>

            {loading && <p className={styles.loadingText}>Loading Google reviews...</p>}
            {!loading && !displayReviews.length && (
              <p className={styles.loadingText}>No Google reviews are available right now.</p>
            )}
            {!loading && review && (
              <>
                <div className={`${styles.reviewCard} ${animating ? styles.fadeOut : styles.fadeIn}`}>
                  <div className={styles.quoteMark}>&ldquo;</div>
                  <p className={styles.reviewText}>{review.text}</p>

                  <div className={styles.reviewer}>
                    <div className={styles.avatar}>{review.initials}</div>
                    <div>
                      <p className={styles.reviewerName}>{review.name}</p>
                      <p className={styles.reviewDate}>{review.role}</p>
                    </div>
                    {/* <div className={styles.reviewRating}>{'★'.repeat(review.rating)}</div> */}
                  </div>
                </div>

                <div className={styles.controls}>
                  <div className={styles.dots}>
                    {displayReviews.map((_, i) => (
                      <button
                        key={i}
                        className={`${styles.dot} ${i === current ? styles.dotActive : ''}`}
                        onClick={() => goTo(i)}
                        aria-label={`Go to review ${i + 1}`}
                      />
                    ))}
                  </div>
                  <div className={styles.navButtons}>
                    <button className={styles.navBtn} onClick={prev} aria-label="Previous">
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
                    </button>
                    <button className={styles.navBtn} onClick={next} aria-label="Next">
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
                    </button>
                  </div>
                </div>
              </>
            )}
          </div>

        </div>
      </div>
    </section>
  );
}
