"use client";

import { useState, useRef, useEffect } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import Image from "next/image";
import { withCDN, optimizedImage } from "@/src/lib/utils";
import type { TestimonialsData } from "@/src/lib/types/home";
import TestimonialSwiper from "./TestimonialSlider";

export default function ParentsTestimonial({
  data,
}: {
  data: TestimonialsData;
}) {
  const { 
    testimonials = [], 
    mainHeading, 
    title,
    subHeading, 
    feature1, 
    feature2, 
    feature3, 
    feature4,
    parentNotices 
  } = data || {};

  // Use dynamic mainHeading if available, otherwise fall back to title
  const displayHeading = mainHeading || title;

  // Build dynamic features array from feature1, feature2, feature3, feature4
  const dynamicFeatures = [feature1, feature2, feature3, feature4].filter(Boolean);

  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);
  const [backgroundImage, setBackgroundImage] = useState("");
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const checkScroll = () => {
    if (scrollContainerRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } =
        scrollContainerRef.current;
      setCanScrollLeft(scrollLeft > 0);
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
    }
  };

  const updateBackgroundImage = () => {
    const width = window.innerWidth;
    if (width < 768) {
      // Mobile
      setBackgroundImage(withCDN("/testimonialsMobile.svg"));
    } else if (width >= 768 && width < 1024) {
      // Tablet
      setBackgroundImage(withCDN("/testimonialsTab.svg"));
    } else {
      // Desktop
      // The two smaller breakpoints are SVG, which optimizedImage passes
      // through untouched; this one is a 1 MB PNG.
      setBackgroundImage(optimizedImage(withCDN("/testimonials.png"), 1920));
    }
  };

  useEffect(() => {
    checkScroll();
    updateBackgroundImage();

    const handleResize = () => {
      checkScroll();
      updateBackgroundImage();
    };

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const scroll = (direction: "left" | "right") => {
    if (scrollContainerRef.current) {
      const scrollAmount = 600;
      scrollContainerRef.current.scrollBy({
        left: direction === "left" ? -scrollAmount : scrollAmount,
        behavior: "smooth",
      });
      setTimeout(checkScroll, 300);
    }
  };

  const swiperInstance = useRef<any>(null);

  // Use dynamic features if available, otherwise fall back to parentNotices
  const hasFeatures = dynamicFeatures.length > 0;
  const displaySubHeading = subHeading || parentNotices?.text;
  const displayIcons = hasFeatures
    ? dynamicFeatures.map((feature, index) => ({
        image: parentNotices?.icons?.[index]?.image || withCDN("/placeholder.svg"),
        alt: parentNotices?.icons?.[index]?.alt || `Feature ${index + 1}`,
        text: feature,
      }))
    : parentNotices?.icons || [];

  return (
    <section
className="relative w-full overflow-hidden bg-transparent px-2 md:px-10 lg:px-14 xl:px-16 min-h-[1080px] md:min-h-[1140px] z-50 top-[-70px] md:top-[-10px] max-[370px]:min-h-[1250px]"      style={{
        backgroundImage: `url('${backgroundImage}')`,
        backgroundSize: "cover",
        backgroundPosition: "top",
        backgroundRepeat: "no-repeat",
      }}
    >
      <div className="max-w-[1300px] mx-auto w-full  xl:px-0 sm:pt-34 md:pt-26 px-4 mt-[200px] sm:mt-[120px] md:mt-[100px] md:mt-12">
        {/* Heading */}
        <h2 className="text-[30px]  2xl:text-[50px] lg:text-[40px] xl:text-[40px] font-bold text-white mb-6 sm:mb-14 md:mb-2  uppercase ">
          {displayHeading}
        </h2>

        {/* Testimonials */}
            <TestimonialSwiper testimonials={testimonials}  />
        {/* Icons Row Section */}
        <div className="pr-0 sm:pr-4 xl:pr-30 testimonial-icons-row">
        {/* Mobile/Tablet: 2x2 grid with icon next to text in each cell */}
          <div className="block md:hidden text-left pt-2">
            <p className="text-white font-bold uppercase text-[14px] sm:text-[16px] leading-[22px] tracking-wide mb-4 sm:mb-6">
              {displaySubHeading}
            </p>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-6">
              {displayIcons.map((icon, index) => (
                <div
                  key={index}
                  className="flex flex-row items-center gap-2 sm:gap-3 text-white"
                >
                  <Image
                    src={icon.image || withCDN("/placeholder.svg")}
                    alt={icon.alt}
                    width={56}
                    height={56}
                    className="w-[48px] h-[48px] sm:w-[56px] sm:h-[56px] flex-shrink-0"
                  />
                  <p className="text-[13px] sm:text-[13px] leading-tight">
                    {icon.text}
                  </p>
                </div>
              ))}
            </div>
          </div>

          <div className="hidden md:grid xl:grid-cols-[40%_60%] md:grid-cols-[30%_70%] items-center gap-6 mt-8">
            {/* Left column */}
            <div className="self-center">
              <p className="text-white font-bold uppercase text-[16px] xl:text-[24px] leading-tight max-w-[430px] lg:w-[80%] xl:w-full xl:inline">
                {displaySubHeading}
              </p>
            </div>

            {/* Right column - icons */}
            <div className="flex items-center justify-start">
              <div className="grid grid-cols-4 gap-6 lg:gap-8 justify-start">
                {displayIcons.map((icon, index) => (
                  <div
                    key={index}
                    className="
                    flex flex-col items-center text-left
                    box-border overflow-hidden p-3
                    w-[150px] md:w-[140px] lg:w-[150px] xl:w-[170px]
                    min-w-[140px]
        "
                  >
                    {/* icon */}
                    <div className="w-[64px] h-[64px] md:w-[70px] md:h-[70px] xl:w-[100px] xl:h-[100px] flex items-start justify-center mb-3">
                      <Image
                        src={icon.image || withCDN("/placeholder.svg")}
                        alt={icon.alt}
                        width={160}
                        height={160}
                        className="w-full h-full object-contain"
                      />
                    </div>

                    {/* text */}
                    <p className="mt-1 text-white text-[12px] md:text-[10px] text-center xl:text-[14px] leading-tight">
                      {icon.text}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
