import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import { useStores } from '@/app/(root)/AppProviders';
import Button from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';

import UserCard from '../search/UserCard';

const LibraryFollowers = observer<any>(({}) => {
  const { library } = useStores();
  const [pagesLoaded, setPagesLoaded] = useState(1);
  const [numTotalProfiles, setNumTotalProfiles] = useState<number | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const { ref: spinnerRef } = useInView({
    threshold: 0,
    onChange: async (inView) => {
      if (inView) {
        const { numTotalProfiles } = await library.loadFollowers(
          pagesLoaded + 1
        );
        setPagesLoaded(pagesLoaded + 1);
        setNumTotalProfiles(numTotalProfiles);
      }
    },
  });

  useEffect(() => {
    const loadInitialProfiles = async () => {
      const { numTotalProfiles } = await library.loadFollowers();
      setNumTotalProfiles(numTotalProfiles);
      setIsLoading(false);
    };
    loadInitialProfiles();
  }, []);

  if (isLoading) {
    return (
      <div className='flex h-full w-full items-center justify-center'>
        <SpinnerSVG />
      </div>
    );
  }

  return library.followers?.length ? (
    <>
      <div className='flex flex-row flex-wrap gap-4 px-6 py-4'>
        {library.followers.map((profile: any) => (
          <UserCard
            key={profile.user_id}
            display_name={profile.display_name}
            avatar_image_url={profile.avatar_image_url}
            handle={profile.handle}
            followers_count={profile.stats?.['followers_count']}
          />
        ))}
      </div>
      {library.followers.length < (numTotalProfiles || 0) && (
        <div className='flex w-full items-center justify-center'>
          <SpinnerSVG ref={spinnerRef} />
        </div>
      )}
    </>
  ) : (
    <>
      <div className='mt-20 flex w-full flex-col items-center gap-8'>
        <span className='text-md font-sans text-foreground-secondary'>
          {"There's nothing here yet."}
        </span>
        <Button href='/'>Back to Home Page</Button>
      </div>
    </>
  );
});
export default LibraryFollowers;
