import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useRecoilState, useRecoilValue } from 'recoil';

import { sessionStore } from '../../stores';
import { AREAS, collectionStore } from './stores';
import Dropzone from './components/upload/Dropzone';
import Collection from './components/collection/collection';

const PlaylistsRoute = () => {
  const navigate = useNavigate();
  const [collection, setCollection] = useRecoilState(collectionStore);
  const session = useRecoilValue(sessionStore);

  /**
   * Tab between the public/private areas and load associated images
   * @param area
   */
  const handleChangeTab: (area: AREAS) => void = (area) =>
    setCollection({
      ...collection,
      selectedArea: area,
    });

  // If the user is not authed redirect them to the home page
  useEffect(() => {
    if (!session.loading && !session.session) {
      navigate('/');
    }
  }, [session, navigate]);

  return (
    <div className="p-2 text-center mb-14">
      {session.session && (
        <>
          <div className="flex items-center justify-center m-auto translate-y-1/2 w-fit">
            <div className="overflow-hidden border-2 rounded-lg tabs border-base-content">
              {Object.keys(AREAS).map((area) => (
                <button
                  type="button"
                  key={area}
                  onClick={() => handleChangeTab(AREAS[area as AREAS])}
                  className={`tab h-10 font-bold text-sm ease-in ${collection.selectedArea === AREAS[area as AREAS]
                      ? 'tab-active bg-base-content text-base-100'
                      : 'bg-base-100 text-base-content'
                    } ease-in`}
                >
                  {`${AREAS[area as AREAS].charAt(0).toUpperCase()}${AREAS[
                    area as AREAS
                  ]
                    .slice(1)
                    .toLowerCase()}`}
                </button>
              ))}
            </div>
          </div>

          <Dropzone>
            <Collection />
          </Dropzone>
        </>
      )}
    </div>
  );
};

export default PlaylistsRoute;