import React from 'react';
import './SelectSubjects.css';
import { Button, Form, Space, message, Input, Upload, Typography, Image } from 'antd';
import ImgCrop from 'antd-img-crop';
import { FormOutlined, CheckSquareTwoTone, CloseSquareTwoTone, UploadOutlined } from '@ant-design/icons';
import { authenticationService } from '../../_services';
import { selectorService } from '../../services/selectorService';
import { S3Bucket } from '../../services/S3Bucket';
import empty from '../EmptyImage';
import { withTranslation } from 'react-i18next';

let subject = [];

class SelectSubjects extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentUser: authenticationService.currentUserValue,
      classId: authenticationService.currentClassValue,
      examName: props.selectorState.name,
      update: false,
      examId: props.selectorState.examId,
      sections: [],
      currentUser: authenticationService.currentUserValue,
      authorId: props.selectorState.authorId,
      examStatus: props.selectorState.examStatus,
      examTypeId: props.selectorState.examTypeId,
      id: props.selectorState.id,
      image: props.selectorState.image,
      instituteId: props.selectorState.instituteId,
      isActive: props.selectorState.isActive,
      languageId: props.selectorState.languageId,
      subjects: [],
      editing: false,
      updatedName: props.selectorState.name,
      number: 0,
      file: "",
      uploading: false,

    };

    this.uploadProps = {
      onRemove: (file) => {
        this.setState(prev => ({...prev, file: ""}));
      },
      beforeUpload: async (file) => {
        this.setState(prevVal => {
          return {
            ...prevVal,
            file,
            uploading: true,
          }
        });
        
        try {
          // uploading to S3 bucket and getting a link in return
          const linkReturn = await S3Bucket.examImageUpload(this.state.id, file);
          // updating the image variable
          this.setState(prev => ({...prev, image: linkReturn, uploading: false}));
          message.success("Image successfully changed!")
        } catch (error) {
          message.error("Could not upload image. Please try again.");
        }

        return false;
      },
      onchange: (err, event) => console.log('event'),
      file: this.state.file,
    };

    this.addImageDefault = () => {
      this.setState (prev => {
        return { ...prev, image: empty() }
      });
    }

    this.handleSubjectSelection = this.handleSubjectSelection.bind(this);
    this.onTextChange = this.onTextChange.bind(this);
    this.sendData = this.sendData.bind(this);
    this.handleLoadSubjects = this.handleLoadSubjects.bind(this);
    this.handleSubjectButtonClick = this.handleSubjectButtonClick.bind(this);
    this.checkType = this.checkType.bind(this);
  }

  handleSubjectButtonClick(index) {

    let tempSubjects = this.state.subjects;
    tempSubjects[index].buttonState = !tempSubjects[index].buttonState;
    let array = this.state.subjects.filter(x => x.buttonState);
    this.setState({ subjects: tempSubjects, number: array.length });
    // this.forceUpdate();
  }

  componentDidMount() {
    this.handleLoadSubjects();
  }
  onTextChange = (event) => {
    this.setState({
      examName: event.target.value,
      update: true
    });
  }
  handleLoadSubjects = () => {
    selectorService.loadSubjects(this.state.classId).then(data => {
      // console.log('Success:', data);
      const result = data.result;
      this.state.subjects = [];
      for (let index = 0; index < result.length; index++) {
        let c = {};
        c.label = (result[index]).name;
        c.value = (result[index]).id;
        c.index = index;
        c.buttonState = false;
        this.state.subjects.push(c);
      }
      selectorService.loadSections(this.state.id).then((data) => {
        if(+data.status.code < 0) {
          console.log("No section pre-exist");
        } else {
          let countTrue = 0;
          const result = data.result.sections;
          let tempSubjects = this.state.subjects;
          for(let item of result) {
            for(let eleIndex = 0; eleIndex < tempSubjects.length; eleIndex++) {
              if(item.subject_id === tempSubjects[eleIndex].value) {
                countTrue++;
                tempSubjects[eleIndex].buttonState = true;
              }
            }
          }
          this.setState({ subjects: tempSubjects, number: countTrue, sections: result });
        }
        if(this.state.number > 0) {
          result.current = 2;
          result.sections = this.state.sections;
          result.image = this.state.image;
          // console.log(this.state.examName);
          result.name = this.state.examName;
          message.success({ content: 'Sections already attached! Going to step 3', duration: 3 });
          this.sendData(result);
        }
      }).catch(err => {
        console.log(err);
        message.info("Something went wrong, please reload!!");
      });;
      this.forceUpdate();
    }).catch(err => {
      console.log(err);
      message.info("Something went wrong, please reload!!");
    });
  }
  handleSubjectSelection() {
    if (this.state.number === 0) {
      message.warning('Select subjects to continue');
    }
    else {
      let subjectsId = [];
      this.state.subjects.forEach(subject => {
        if (subject.buttonState) {
          subjectsId.push(subject.value);
          this.state.sections.push(subject);
        }
      });
      let json = {};
      json.idList = subjectsId;
      json.name = this.state.examName;
      message.loading({ content: 'Attaching Sections...' });
      selectorService.attachSectionToExam(this.state.id, json).then(data => {
        let result = {};
        
        if(+data.status.code < 0) throw data.status.message[0];

        result.current = 2;
        result.sections = this.state.sections;
        result.image = this.state.image;
        // console.log(this.state.examName);
        result.name = this.state.examName;
        message.success({ content: 'Sections Attached!', duration: 3 });
        this.sendData(result);
      }).catch(err => {
        console.log(err);
        message.info({ content: 'Something went wrong, please try again later', duration: 3 });
      });
    }

  }
  sendData = (result) => {
    // console.log(result);
    this.props.parentCallback(result);
  }

  checkType = (file) => {
    if (file.type === "image/png") {
      return true;
    } else {
      message.error("Please select PNG files for Exam Icon");
      return false;
    }
  }

  render() {
    return (
      <div className='SelectSubjects'>
        <Form className="exam-form">
          <div className='exam'><table className='examTable'>
            <tbody>
              <tr>
                <td>
                  <div className='examNameOuter'>
                    <div>
                      <Image 
                        // onError={this.addImageDefault} 
                        fallback={empty()}
                        width={100} 
                        height={100} 
                        src={`${this.state.image}?${Date.now()}`} />
                      <div className='center-flex hovering-uploader' data-button-state={this.state.uploading? "loading" : "idle"}>
                      <ImgCrop beforeCrop={this.checkType}>
                        <Upload {...this.uploadProps} maxCount={1} showUploadList={false}>
                          <Button size="small" loading={this.state.uploading} icon={<UploadOutlined />}>
                            <span style={{display: this.state.uploading? "none":"inline-block"}}>{this.props.t('change-btn')}</span>
                          </Button>
                        </Upload>
                      </ImgCrop>
                    </div>
                    </div>

                    <div className='examName'>
                      <div>
                        <Typography.Text style={{color: 'var(--font-color-primary)', fontSize: '0.85rem'}}>{this.props.t('exam-name')}</Typography.Text>
                      </div>
                      <div>
                        <span hidden={this.state.editing} className='examNameSpan'>{this.state.examName}</span>
                        <span> <Input value={this.state.updatedName} onChange={(e) => this.setState({ updatedName: e.target.value })}
                          hidden={!this.state.editing} style={{ width: '60%' }} placeholder="Enter Exam Name" />
                        </span>
                      </div>
                    </div>
                  </div>
                </td>
                <td className='examNameEdit' style={{ cursor: 'pointer', width: '5px' }} >
                  <div onClick={() => this.setState({ editing: true })}>
                    <FormOutlined hidden={this.state.editing} style={{ fontSize: '16px', color: '#1890FF' }} twoToneColor='#1890FF' />
                  </div>
                  <div hidden={!this.state.editing} onClick={() => { this.setState({ editing: false, updatedName: this.state.examName }) }}>
                    <CloseSquareTwoTone />
                  </div>
                  <div onClick={() => {
                    const { examId, updatedName, image, authorId, examTypeId, id } = this.state;
                    selectorService.updateExam({ id, examId, name: updatedName, image, authorId, examTypeId })
                      .then((res) => { 
                        this.setState({ editing: false, examName: this.state.updatedName });
                      }).catch((err) => { console.log("Failed! - "+ err); this.setState({ editing: false, updatedName: this.state.examName }) });
                  }} hidden={!this.state.editing}>
                    <CheckSquareTwoTone />
                  </div>
                </td>
              </tr>
            </tbody>
          </table></div>


          <br />
          <div className="select-subject-grid">
          <Typography.Text strong 
            style={{color: 'var(--font-color-primary)', fontSize: '0.85rem',paddingTop: '1rem', alignSelf: 'start'}}>
              {this.props.t('select-sub')}
          </Typography.Text>
          {/* <br /> */}
          <div className='subjectButtons'>
            {/* <Space> */}
              {this.state.subjects.map((subject, index) => {
                return (
                  <Button
                    onClick={() => this.handleSubjectButtonClick(index)}
                    className={subject.buttonState ? 'subjectButtonTrue' : 'subjectButtonFalse'}
                    // style={{ color: subject.buttonState ? '#1890FF' : '#cccccc', borderColor: subject.buttonState ? '#1890FF' : '#cccccc' }}
                    key={index}
                    title={subject.label} >{subject.label}</Button>
                )
              })}
            {/* </Space> */}
          </div>
          </div>
          <br />
        </Form>
        <div data-need-margin={"false"} className='button-container'>
          <Button type="primary" onClick={e => { this.handleSubjectSelection() }}>{this.props.t('continue-btn')}</Button>
        </div>
      </div>
    )
  };
};

export default withTranslation()(SelectSubjects);
