import PropTypes from 'prop-types';
import classNames from 'classnames';
import Badge from '../badge';
import Button from '../../shared/buttons/button';
import { RefreshIcon } from '@heroicons/react/outline';
import { compareChapter } from '../utils';

function StudentDeck({ priority, rateType, studentDeck, onSelectChapter, onRefreshSelected }) {
  function getURL(chapterId, cardType) {
    const url = `/cards/ch-${chapterId}/${cardType}`;
    const urlSearchParams = new URLSearchParams();
    if (priority) urlSearchParams.set('priority', priority);
    if (cardType !== 'new' && rateType) urlSearchParams.set('rate-type', rateType);
    const urlSearchParamsSTR = urlSearchParams.toString();
    if (!urlSearchParamsSTR) return url;
    return url + `?${urlSearchParamsSTR}`;
  }

  return studentDeck.deck.chapters.sort(compareChapter).map((chapter, index, array) => (
    <div
      key={chapter.id}
      onClick={e => {
        e.stopPropagation();
        onSelectChapter(chapter);
      }}
      className={classNames('border border-t-0 border-gray-500 text-center', {
        'rounded-b-lg': index === array.length - 1
      })}
    >
      <div className='relative grid grid-flow-col grid-cols-9 p-4 hover:bg-gray-100 sm:grid-flow-row'>
        <div className='row-span-3 m-auto'>({index + 1})</div>
        <div className='col-span-8 m-auto sm:col-span-3'>{chapter.name}</div>
        <div className='col-span-8 my-2 flex justify-center gap-2 sm:col-span-4 sm:my-auto'>
          <Badge
            text='مروری'
            number={chapter.reviewCardCount}
            to={getURL(chapter.id, 'review')}
            color='red'
          />
          <Badge
            text='جدید'
            number={chapter.newCardCount}
            to={getURL(chapter.id, 'new')}
            color='yellow'
          />
        </div>
        {!rateType && (
          <div className='row-span-3 m-auto font-bold'>
            <Button
              outline
              circular
              size='xs'
              color='orange'
              disabled={chapter.cardCount === chapter.newCardCount}
              onClick={e => {
                e.stopPropagation();
                onRefreshSelected({ id: chapter.id, type: 'chapter', name: chapter.name });
              }}
            >
              <RefreshIcon width={20} height={20} />
            </Button>
          </div>
        )}
      </div>
    </div>
  ));
}

StudentDeck.propTypes = {
  priority: PropTypes.string,
  rateType: PropTypes.string,
  studentDeck: PropTypes.object.isRequired,
  onSelectChapter: PropTypes.func.isRequired,
  onRefreshSelected: PropTypes.func.isRequired
};

export default StudentDeck;
