import { useEffect, useState } from 'react';
import { useRecoilValue } from 'recoil';

import { AREAS, collectionStore } from '../../stores';
import { getPlaylistsFromWNFS, type Playlist } from '../../lib/playlists';
import FileUploadCard from '../upload/FileUploadCard';
import PlaylistCard from './playlistCard';
import PlaylistModal from './playlistModal';

const Collection = () => {
  const collection = useRecoilValue(collectionStore);

  const [selectedArea, setSelectedArea] = useState<string | null>(
    collection.selectedArea
  );
  const [selectedPlaylist, setSelectedPlaylist] = useState<Playlist | null>(
    null
  );

  const selectedCollection =
    collection.selectedArea === AREAS.PRIVATE
      ? collection.privatePlaylists
      : collection.publicPlaylists;

  /**
   * Open the ImageModal and pass it the selected `image` from the gallery
   * @param image
   */
  const handleOpenModal: (playlist: Playlist) => void = (playlist) =>
    setSelectedPlaylist(playlist);

  const clearSelectedPlaylist = () => setSelectedPlaylist(null);

  useEffect(() => {
    // If collectionStore.selectedArea changes from private to public, re-run getPlaylistsFromWNFS
    if (!collection.loading && selectedArea !== collection.selectedArea) {
      const refetchPlaylists = async () => {
        setSelectedArea(collection.selectedArea);
        await getPlaylistsFromWNFS();
      };
      refetchPlaylists();
    }
    // eslint-disable-next-line
  }, [collection.selectedArea, selectedArea]);

  const useMountEffect = () =>
    useEffect(() => {
      // Get images from the user's public WNFS
      getPlaylistsFromWNFS();
    }, []);

  useMountEffect();

  return (
    <section className="overflow-hidden text-gray-700">
      <div className="p-6 pt-8 mx-auto md:p-8">
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4 xl:lg:grid-cols-6">
          <FileUploadCard />
          {selectedCollection?.map((playlist: Playlist) => (
            <PlaylistCard
              key={playlist.cid}
              playlist={playlist}
              openModal={handleOpenModal}
            />
          ))}
        </div>
      </div>

      {selectedPlaylist && (
        <PlaylistModal
          playlist={selectedPlaylist}
          isModalOpen={!!selectedPlaylist}
          onClose={clearSelectedPlaylist}
        />
      )}
    </section>
  );
};

export default Collection;