import { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {
  InformationCircleIcon,
  MinusCircleIcon,
  PlusCircleIcon,
  RefreshIcon
} from '@heroicons/react/outline';
import { getStudentDeckComparator } from './utils';
import Badge from './badge';
import Button from '../shared/buttons/button';
import ChapterModal from './chapter-modal';
import ResetModal from './reset-modal';
import StudentDeckContainer from './student-deck/container';

class StudentDecks extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedStudentDeck: props.studentDecks.length === 1 ? props.studentDecks[0] : null,
      selectedChapter: null,
      selectedRefreshItem: null
    };
  }

  isSelectedStudentDeck = studentDeckId => this.state.selectedStudentDeck?.id === studentDeckId;

  handleSelectStudentDeck = studentDeck =>
    this.setState(state => ({
      selectedStudentDeck: state.selectedStudentDeck?.id === studentDeck.id ? null : studentDeck
    }));

  handleSelectChapter = chapter =>
    this.setState(state => ({
      selectedChapter: state.selectedChapter?.id === chapter?.id ? null : chapter
    }));

  handleRefreshSelected = item =>
    this.setState(state => ({
      selectedRefreshItem: state.selectedRefreshItem?.id === item?.id ? null : item
    }));

  getStudentDeckColor = studentDeck => {
    if (studentDeck.reviewCardCount !== 0) return 'red';
    return studentDeck.newCardCount !== 0 ? 'blue' : 'green';
  };

  render() {
    const comparator = getStudentDeckComparator(this.props.priority);
    return (
      <Fragment>
        <div className='mx-4 rounded-lg'>
          {this.props.studentDecks.sort(comparator).map(studentDeck => {
            if (this.props.priority && !studentDeck.deck.prioritized) {
              return (
                <div key={studentDeck.id} className='mb-1'>
                  <div
                    className={classNames(
                      'grid grid-flow-col grid-cols-9 sm:grid-flow-row ',
                      `bg-gray-100`,
                      'rounded-lg border border-black p-4 text-center'
                    )}
                  >
                    <div className='row-span-3 m-auto'>
                      <InformationCircleIcon width={25} height={25} />
                    </div>
                    <div className='col-span-8 m-auto font-bold sm:col-span-3'>
                      {studentDeck.deck.name}
                    </div>
                    <div className='col-span-8 my-2 flex justify-center gap-2 sm:col-span-4 sm:my-auto'>
                      به زودی
                    </div>
                  </div>
                </div>
              );
            }

            return (
              <div key={studentDeck.id} className='mb-1'>
                <div
                  className={classNames(
                    'grid grid-flow-col grid-cols-9 sm:grid-flow-row ',
                    `bg-${this.getStudentDeckColor(studentDeck)}-100`,
                    { 'rounded-b-lg': !this.isSelectedStudentDeck(studentDeck.id) },
                    'rounded-t-lg border border-black p-4 text-center'
                  )}
                  onClick={() => this.handleSelectStudentDeck(studentDeck)}
                >
                  <div className='row-span-3 m-auto'>
                    {this.isSelectedStudentDeck(studentDeck.id) ? (
                      <PlusCircleIcon width={25} height={25} />
                    ) : (
                      <MinusCircleIcon width={25} height={25} />
                    )}
                  </div>
                  <div className='col-span-8 m-auto font-bold sm:col-span-3'>
                    {studentDeck.deck.name}
                  </div>
                  <div className='col-span-8 my-2 flex justify-center gap-2 sm:col-span-4 sm:my-auto'>
                    <Badge text='مروری' number={studentDeck.reviewCardCount} color='red' />
                    <Badge text='جدید' number={studentDeck.newCardCount} color='yellow' />
                  </div>
                  {!this.props.rateType && (
                    <div className='row-span-3 m-auto font-bold'>
                      <Button
                        outline
                        circular
                        size='xs'
                        color='orange'
                        disabled={studentDeck.deck.cardCount === studentDeck.newCardCount}
                        onClick={e => {
                          e.stopPropagation();
                          this.handleRefreshSelected({
                            id: studentDeck.deck.id,
                            type: 'deck',
                            name: studentDeck.deck.name
                          });
                        }}
                      >
                        <RefreshIcon width={20} height={20} />
                      </Button>
                    </div>
                  )}
                </div>
                {this.isSelectedStudentDeck(studentDeck.id) && (
                  <StudentDeckContainer
                    studentDeckId={studentDeck.id}
                    onSelectChapter={this.handleSelectChapter}
                    onRefreshSelected={this.handleRefreshSelected}
                  />
                )}
              </div>
            );
          })}
        </div>
        {this.state.selectedChapter && (
          <ChapterModal
            chapter={this.state.selectedChapter}
            lessonName={this.state.selectedStudentDeck?.deck.lesson.name}
            priority={this.props.priority}
            rateType={this.props.rateType}
            onClose={() => this.handleSelectChapter(null)}
          />
        )}
        {this.state.selectedRefreshItem && (
          <ResetModal
            itemType={this.state.selectedRefreshItem.type}
            itemId={this.state.selectedRefreshItem.id}
            itemName={this.state.selectedRefreshItem.name}
            onClose={() => this.handleRefreshSelected(null)}
          />
        )}
      </Fragment>
    );
  }
}

StudentDecks.propTypes = {
  priority: PropTypes.string,
  rateType: PropTypes.string,
  studentDecks: PropTypes.array.isRequired,
  history: PropTypes.object.isRequired
};

export default withRouter(StudentDecks);
