import { getLocale, getTranslations } from "next-intl/server";
import TestimonialImageOne from "@/assets/images/testimonials-img-one.jpg";
import TestimonialImageTwo from "@/assets/images/testimonials-img-two.jpg";
import TestimonialImageThree from "@/assets/images/testimonials-img-three.jpg";
import TestimonialCard from "./TestimonialCard";
import { CMSItem, CmsReview } from "@/types/cms";
import { cmsValue, localizedImageUrl, localizedText } from "@/services/cmsService";
import CmsPreviewText from "@/components/preview/CmsPreviewText";

const fallbackImages = [
  TestimonialImageOne,
  TestimonialImageTwo,
  TestimonialImageThree,
];

export default async function TestimonialsGrid({ cms }: { cms: CMSItem[] }) {
  const locale = await getLocale();
  const t = await getTranslations("TestimonialsSection");

  const cmsReviews = cmsValue(cms, "reviews") as CmsReview[] | undefined;

  const testimonials =
    cmsReviews && cmsReviews.length > 0
      ? cmsReviews.map((review, index) => ({
          imageSrc:
            localizedImageUrl(review.image) ||
            fallbackImages[index % fallbackImages.length],
          imageAlt: localizedText(review.name, locale),
          text: localizedText(review.review, locale),
          author: localizedText(review.name, locale),
          imageFirst: index % 2 === 0,
        }))
      : [1, 2, 3].map((n, index) => ({
          imageSrc: fallbackImages[index],
          imageAlt: `Testimonial Image ${n}`,
          text: t(`testimonial${n}.text`),
          author: t(`testimonial${n}.author`),
          imageFirst: index % 2 === 0,
        }));

  return (
    <div className="grid grid-cols-1 sm:grid-cols-3 gap-5 lg:gap-10">
      {testimonials.map((testimonial, index) => (
        <TestimonialCard
          key={index}
          imageSrc={testimonial.imageSrc}
          imageAlt={testimonial.imageAlt}
          itemIndex={index}
          text={
            <CmsPreviewText
              sectionName="customer_reviews"
              inputNameEn="reviews"
              itemIndex={index}
              itemField="review"
              initialValue={testimonial.text}
            />
          }
          author={
            <CmsPreviewText
              sectionName="customer_reviews"
              inputNameEn="reviews"
              itemIndex={index}
              itemField="name"
              initialValue={testimonial.author}
            />
          }
          imageFirst={testimonial.imageFirst}
        />
      ))}
    </div>
  );
}
