"use client";

import { useState, useEffect, useRef, useMemo } from "react";
import dynamic from "next/dynamic";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import type { TestimonialsData } from "@/src/lib/types/home";
import { getTestimonialsAction } from "@/src/lib/actions/testimonialsAction";
import type { GeneralSettings } from "@/src/lib/types/header";
import testimonialsJsonData from "@/src/data/home.json";
import TestimonialSkeleton from "../ui/skeletons/TestimonialSkeleton";

const ParentsTestimonialComponent = dynamic(
  () => import("./ParentsTestimonial/Client"),
  {
    ssr: false,
    loading: () => <TestimonialSkeleton />,
  }
);

interface Testimonial {
  id: string;
  parent_name: string;
  role: string;
  comment: string;
  order_no: number;
  language?: string;
}

interface TestimonialsLazyWrapperProps {
  testimonialsSection?: {
    default?: {
      mainHeading?: string;
      subHeading?: string;
      feature1?: string;
      feature2?: string;
      feature3?: string;
      feature4?: string;
    };
    translated?: {
      mainHeading?: string;
      subHeading?: string;
      feature1?: string;
      feature2?: string;
      feature3?: string;
      feature4?: string;
    };
  };
  generalSettings?: GeneralSettings;
}

export default function TestimonialsLazyWrapper({
  testimonialsSection,
  generalSettings,
}: TestimonialsLazyWrapperProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [testimonialData, setTestimonialData] = useState<TestimonialsData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [hasLoaded, setHasLoaded] = useState(false);
  const { currentLanguage, isInitialized } = useLanguage();
  const prevLanguageRef = useRef<string>(currentLanguage);

  // Select content based on current language, fallback to default or empty object
  const selectedTestimonialSection = useMemo(() => {
    if (!testimonialsSection) return {};
    
    // Use translated content if language is not default
    if (currentLanguage !== "default") {
      return testimonialsSection.translated || testimonialsSection.default || {};
    }
    return testimonialsSection.default || {};
  }, [testimonialsSection, currentLanguage]);

  // Handle language changes - refetch testimonials with new language
  useEffect(() => {
    if (!isInitialized) return;

    if (prevLanguageRef.current !== currentLanguage && hasLoaded) {
      prevLanguageRef.current = currentLanguage;
      setIsLoading(true);

      const params = new URLSearchParams(window.location.search);
      const franchiseeId = params.get("franchiseeId");

      // Use actual currentLanguage if not "default"
      const languageCode = currentLanguage === "default" ? null : currentLanguage;

      getTestimonialsAction(franchiseeId, languageCode)
        .then((response) => {
          if (response.success && Array.isArray(response.data)) {
            console.log(`[TestimonialsLazyWrapper] Refetched testimonials with language: ${languageCode || "default"}`);
            const testimonials = response.data
              .sort((a: Testimonial, b: Testimonial) => a.order_no - b.order_no)
              .map((t: Testimonial, index: number) => ({
                id: index + 1,
                quote: t.comment,
                author: `${t.parent_name}, ${t.role}`,
              }));

            setTestimonialData((prev) => ({
              testimonials,
              mainHeading: selectedTestimonialSection?.mainHeading || testimonialsJsonData.testimonials.title,
              subHeading: selectedTestimonialSection?.subHeading || testimonialsJsonData.testimonials.parentNotices.text,
              feature1: selectedTestimonialSection?.feature1,
              feature2: selectedTestimonialSection?.feature2,
              feature3: selectedTestimonialSection?.feature3,
              feature4: selectedTestimonialSection?.feature4,
              title: selectedTestimonialSection?.mainHeading || testimonialsJsonData.testimonials.title,
              subtitle: prev?.subtitle || testimonialsJsonData.testimonials.subtitle,
              parentNotices: prev?.parentNotices || testimonialsJsonData.testimonials.parentNotices,
            }));
          }
        })
        .catch((error) => {
          console.error("[TestimonialsLazyWrapper] Error refetching testimonials on language change:", error);
        })
        .finally(() => {
          setIsLoading(false);
        });
    }
  }, [currentLanguage, hasLoaded, isInitialized, selectedTestimonialSection]);

  // Initial load
  useEffect(() => {
    if (!isInitialized || hasLoaded || isLoading) return;

    const currentRef = ref.current;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !hasLoaded) {
          setIsLoading(true);

          const params = new URLSearchParams(window.location.search);
          const franchiseeId = params.get("franchiseeId");

          const languageCode = currentLanguage === "default" ? null : currentLanguage;

          getTestimonialsAction(franchiseeId, languageCode)
            .then((response) => {
              if (response.success && Array.isArray(response.data)) {
                console.log(`[TestimonialsLazyWrapper] Initial load with language: ${languageCode || "default"}`);
                const testimonials = response.data
                  .sort((a: Testimonial, b: Testimonial) => a.order_no - b.order_no)
                  .map((t: Testimonial, index: number) => ({
                    id: index + 1,
                    quote: t.comment,
                    author: `${t.parent_name}, ${t.role}`,
                  }));

                setTestimonialData({
                  testimonials,
                  mainHeading: selectedTestimonialSection?.mainHeading || testimonialsJsonData.testimonials.title,
                  subHeading: selectedTestimonialSection?.subHeading || testimonialsJsonData.testimonials.parentNotices.text,
                  feature1: selectedTestimonialSection?.feature1,
                  feature2: selectedTestimonialSection?.feature2,
                  feature3: selectedTestimonialSection?.feature3,
                  feature4: selectedTestimonialSection?.feature4,
                  title: selectedTestimonialSection?.mainHeading || testimonialsJsonData.testimonials.title,
                  subtitle: testimonialsJsonData.testimonials.subtitle,
                  parentNotices: testimonialsJsonData.testimonials.parentNotices,
                });
                setHasLoaded(true);
                prevLanguageRef.current = currentLanguage;
              }
            })
            .catch((error) => {
              console.error("[TestimonialsLazyWrapper] Failed to load testimonials:", error);
            })
            .finally(() => {
              setIsLoading(false);
            });

          if (ref.current) {
            observer.unobserve(ref.current);
          }
        }
      },
      { rootMargin: "200px" }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (currentRef) {
        observer.unobserve(currentRef);
      }
      observer.disconnect();
    };
  }, [hasLoaded, isLoading, isInitialized, currentLanguage, selectedTestimonialSection]);

  return (
    <div className="testimonial-outer-wrapper" ref={ref} style={{ minHeight: "200px" }}>
      {testimonialData && !isLoading ? (
        <ParentsTestimonialComponent data={testimonialData} />
      ) : (
        <TestimonialSkeleton />
      )}
    </div>
  );
}
