import { TabsContent } from "@/components/ui/tabs";
import ActionCard from "./action-card";
import { TLogItem } from "@/services/types/logs.type";
import { TLogAction } from "@/shared/types/home/logs";
import { Skeleton } from "@/components/ui/skeleton";
import ErrorMessage from "@/shared/components/error-message";
import { useEffect, useRef, useCallback } from "react";
import { FetchNextPageOptions } from "@tanstack/react-query";

type TTabContentProps = {
  value: string;
  logs: TLogItem[];
  status: TLogAction;
  error?: Error | null;
  isLoading?: boolean;
  hasNextPage?: boolean;
  isFetchingNextPage?: boolean;
  fetchNextPage?: (options?: FetchNextPageOptions) => Promise<any>;
};

const TabContent = ({
  value,
  logs,
  status,
  isLoading,
  error,
  hasNextPage,
  isFetchingNextPage,
  fetchNextPage
}: TTabContentProps) => {
  const loadMoreRef = useRef<HTMLDivElement>(null);

  // Intersection Observer callback for infinite scroll
  const handleIntersection = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      const [entry] = entries;
      if (entry.isIntersecting && hasNextPage && !isFetchingNextPage && fetchNextPage) {
        fetchNextPage();
      }
    },
    [hasNextPage, isFetchingNextPage, fetchNextPage]
  );

  // Set up intersection observer
  useEffect(() => {
    const observer = new IntersectionObserver(handleIntersection, {
      threshold: 0.1,
      rootMargin: '20px',
    });

    const currentRef = loadMoreRef.current;
    if (currentRef) {
      observer.observe(currentRef);
    }

    return () => {
      if (currentRef) {
        observer.unobserve(currentRef);
      }
    };
  }, [handleIntersection]);

  return (
    <TabsContent className='flex-1 overflow-y-auto pb-4' value={value}>
      <div className='flex flex-col gap-4'>
        {isLoading ? (
          <div className="flex flex-col space-y-4">
            {Array.from({ length: 6 }).map((_, index) => (
              <div className="flex items-center space-x-4" key={index}>
                <Skeleton className="h-12 w-12 rounded-full" />
                <div className="space-y-2">
                  <Skeleton className="h-4 w-[250px]" />
                  <Skeleton className="h-4 w-[200px]" />
                </div>
              </div>
            ))}
          </div>
        ) : (
          logs.length === 0 && !error ? (
            <div className="text-center text-gray-500">No logs found</div>
          ) : error ? (
            <ErrorMessage>Error: {error.message}</ErrorMessage>
          ) :
          logs.map((log: TLogItem) => (
            <ActionCard key={log.id} status={status} log={log} />
          ))
        )}

        {/* Load more trigger and loading indicator */}
        {hasNextPage && (
          <div ref={loadMoreRef} className="flex justify-center py-4">
            {isFetchingNextPage ? (
              <div className="flex items-center space-x-4">
                <Skeleton className="h-12 w-12 rounded-full" />
                <div className="space-y-2">
                  <Skeleton className="h-4 w-[250px]" />
                  <Skeleton className="h-4 w-[200px]" />
                </div>
              </div>
            ) : (
              <div className="text-sm text-gray-500">Scroll to load more...</div>
            )}
          </div>
        )}
      </div>
    </TabsContent>
  );
};

export default TabContent;