"use client";

import { useState, useEffect, useRef } from "react";
import dynamic from "next/dynamic";
import { getTeachersAction } from "@/src/lib/actions/teachersAction";
import { ProcessedTeacher } from "@/src/lib/types/home";
import TeacherSkeleton from "../ui/skeletons/TeacherSkeleton";

const ClientTeachers = dynamic(
  () => import("./TeacherScroller/Client"),
  {
    ssr: false,
    loading: () => <TeacherSkeleton />,
  }
);

interface TeachersLazyWrapperProps {
  /**
   * Fired once the teachers request succeeds, with how many came back. Lets the
   * parent section drop itself when the franchise has no instructors — this has
   * to be reported upwards because the fetch only starts after this element
   * scrolls into view.
   */
  onLoaded?: (count: number) => void;
}

export default function TeachersLazyWrapper({ onLoaded }: TeachersLazyWrapperProps = {}) {
  const ref = useRef<HTMLDivElement>(null);
  const [teachersData, setTeachersData] = useState<ProcessedTeacher[] | null>(
    null
  );
  const [isLoading, setIsLoading] = useState(false);
  const [hasLoaded, setHasLoaded] = useState(false);

  // Held in a ref so an inline callback from the parent doesn't retrigger the
  // observer effect on every render.
  const onLoadedRef = useRef(onLoaded);
  onLoadedRef.current = onLoaded;

  useEffect(() => {
    if (hasLoaded || isLoading) return;

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

          // Extract franchiseeId from URL
          const params = new URLSearchParams(window.location.search);
          const franchiseeId = params.get("franchiseeId");

          getTeachersAction(franchiseeId)
            .then((response) => {
              if (response.success && Array.isArray(response.data)) {
                setTeachersData(response.data);
                setHasLoaded(true);
                onLoadedRef.current?.(response.data.length);
              }
            })
            .catch((error) => {
              console.error(
                "[TeachersLazyWrapper] Failed to load teachers:",
                error
              );
            })
            .finally(() => {
              setIsLoading(false);
            });

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

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

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [hasLoaded, isLoading]);

  return (
    <div ref={ref}>
      {teachersData ? (
        <ClientTeachers teachers={teachersData} />
      ) : (
        <TeacherSkeleton />
      )}
    </div>
  );
}
