import Fetcher from '../../shared/fetches/fetcher';
import PropTypes from 'prop-types';
import StudentDeck from './student-deck';
import Loader from '../../shared/loader';
import { useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import { fetchStudentDeck } from '../../../redux/actions/student-deck';

function StudentDeckContainer({ studentDeckId, onSelectChapter, onRefreshSelected }) {
  const location = useLocation();
  const urlSearchParams = new URLSearchParams(location.search);
  const rateType = urlSearchParams.get('rate-type');
  const priority = urlSearchParams.get('priority');

  const action = useCallback(() => {
    const minRate = rateType ? { starred: 1, active: 0 }[rateType] : -1;
    return fetchStudentDeck(studentDeckId, priority, minRate);
  }, [studentDeckId, priority, rateType]);

  const renderLoader = useCallback(
    () => (
      <div className='border border-t-0 border-gray-500 text-center'>
        <Loader full={false} />
      </div>
    ),
    []
  );

  return (
    <Fetcher action={action} stateSelector={state => state.studentDeck} renderLoader={renderLoader}>
      {studentDeck => (
        <StudentDeck
          priority={priority}
          rateType={rateType}
          studentDeck={studentDeck}
          onSelectChapter={onSelectChapter}
          onRefreshSelected={onRefreshSelected}
        />
      )}
    </Fetcher>
  );
}

StudentDeckContainer.propTypes = {
  studentDeckId: PropTypes.number.isRequired,
  onSelectChapter: PropTypes.func.isRequired,
  onRefreshSelected: PropTypes.func.isRequired
};

export default StudentDeckContainer;
