'use client';

/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */

/* eslint react-hooks/exhaustive-deps: warn */
import { useEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import { useLibrary } from '@/hooks/useLibrary';
import { Clip } from '@/state/clipStore';

import { OrpheusClipRow } from '../clipBrowser/OrpheusClipRow';
import SpinnerSVG from '../svg/SpinnerSVG';
import Modal from './Modal';

type LibrarySelectModalProps = {
  onClose: () => void;
  isOpen: boolean;
};

const LibrarySelectModal: React.FC<LibrarySelectModalProps> = ({
  isOpen,
  onClose,
}: LibrarySelectModalProps) => {
  const { error, loadNextPage } = useLibrary({
    //filters: { isUpload: true },
  });
  const [loadedClips, setLoadedClips] = useState<Clip[]>([]);
  const [showErrorMessage, setShowErrorMessage] = useState<boolean>(false);
  const [shouldInfiniteLoad, setShouldInfiniteLoad] = useState<boolean>(true);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const { inView, ref: infiniteLoadRef } = useInView();

  useEffect(() => {
    const loadPageOnScroll = async () => {
      const nextPageClips = await loadNextPage();
      if (nextPageClips !== null && nextPageClips.length > 0) {
        setLoadedClips([...loadedClips, ...nextPageClips]);
        if (!shouldInfiniteLoad) {
          setShouldInfiniteLoad(true);
        }
      } else {
        setShouldInfiniteLoad(false);
      }
    };
    if (inView && !isLoading) {
      loadPageOnScroll();
    }
  }, [inView]);

  useEffect(() => {
    const loadFirstPage = async () => {
      const firstPageClips = await loadNextPage(0);
      setIsLoading(false);
      if (firstPageClips !== null) {
        setLoadedClips(firstPageClips);
        if (!shouldInfiniteLoad) {
          setShouldInfiniteLoad(true);
        }
      } else {
        setShowErrorMessage(true);
      }
    };
    loadFirstPage();
  }, []);

  if (!isOpen) return null;
  return (
    <Modal width={600} onClose={onClose} wrapperClasses='mt-8'>
      {showErrorMessage ? (
        <div className='flex w-full flex-row justify-center p-8'>
          <span>{error}</span>
        </div>
      ) : isLoading ? (
        <div className='flex h-full w-full flex-row items-center justify-center p-8'>
          <SpinnerSVG />
        </div>
      ) : (
        <div className='h-[400px] overflow-y-auto'>
          {loadedClips.length === 0 ? (
            <span className='w-full text-center'>No clips loaded</span>
          ) : null}
          {loadedClips.map((clip: Clip, i: number) => (
            <OrpheusClipRow
              key={i}
              clipId={clip.id}
              onClick={() => {
                onClose();
              }}
            />
          ))}
          {shouldInfiniteLoad ? (
            <div
              className='flex w-full flex-row justify-center py-4'
              ref={infiniteLoadRef}
            >
              <SpinnerSVG />
            </div>
          ) : null}
        </div>
      )}
    </Modal>
  );
};

export default LibrarySelectModal;
