import React from 'react';
import { Link } from 'react-router-dom';
import DatePicker from 'react-datepicker';
import PropTypes from 'prop-types';

import moment from "moment";

import IDUtil from '../../../util/IDUtil';

class CollectionForm extends React.PureComponent {

    constructor(props) {
        super(props);

        this.collectionName = React.createRef();
        this.description = React.createRef();
        this.creator = React.createRef();

        let dateCreated = null;
        if(this.props.collection.dateCreated){
            let tzOffset = moment(this.props.collection.dateCreated).utcOffset();
            dateCreated = moment(this.props.collection.dateCreated).add(parseInt(tzOffset), 'minutes').toDate();
        }

        this.state = {
            validationError: false,
            dateCreated: dateCreated
        };
        this.CLASS_PREFIX = 'cf'
    }

    handleSubmit = () => {
        const collection = Object.assign({}, this.props.collection);
        collection.name = this.collectionName.current.value;
        collection.description = this.description.current.value;
        collection.dateCreated = this.state.dateCreated;
        collection.creator = this.creator.current.value;
        this.save(collection);

        return false;
    };

    //Save the collection using the Collection API
    save = (collection, callback) => {
        this.props.api.save(this.props.user.id, collection, c => {
            if (c && c.id) {
                this.props.collectionDidSave(c.id);
            } else {
                alert('An error occured while saving this collection');
            }
        });
    };

    validateForm = e => {
        if(this.collectionName.current !== null && this.collectionName.current.value.length !== 0) {
            this.handleSubmit();
        } else {

            this.setState({
                validationError: true
            })
        }
    };

    onDateChanged = date => {
        let dateCreated = null;
        if (date) {
            let tzOffset = moment(date).utcOffset();
            dateCreated = moment(date).add(parseInt(tzOffset), "minutes");
        }
        if(dateCreated) {
            dateCreated = dateCreated.toDate();
            this.setState({dateCreated: dateCreated});
        }
    };

    renderErrorMessage = msg => <div className={IDUtil.cssClassName('validation-error', this.CLASS_PREFIX)}>{msg}</div>;

    render() {
        const errorMessage = this.state.validationError ? this.renderErrorMessage('Please provide a name') : null;

        return (
            <div className={IDUtil.cssClassName('collection-form')}>
                <div>
                    <label className="label">Collection name</label>
                    <input
                        type="text"
                        name="name"
                        defaultValue={this.props.collection.name}
                        ref={this.collectionName}/>
                    <label className="label">Collection description</label>
                    <textarea
                        name="description"
                        defaultValue={this.props.collection.description}
                        ref={this.description}/>
                    <label className="label">Collection date</label>
                    <DatePicker
                        selected={this.state.dateCreated}
                        value={this.state.dateCreated}
                        openToDate={this.state.dateCreated}
                        onChange={this.onDateChanged}
                        showMonthDropdown={true}
                        showYearDropdown={true}
                        dropdownMode="select"
                        className="form-control"
                        placeholderText="Pick a date"
                        dateFormat="dd/MM/yyyy"
                    />
                    <label className="label">Collection creator/organization</label>
                    <input
                        type="text"
                        name="creator"
                        defaultValue={this.props.collection.creator}
                        ref={this.creator}/>
                </div>
                {errorMessage}
                <div className={IDUtil.cssClassName('actions', this.CLASS_PREFIX)}>
                    <Link to={this.props.cancelLink} className="btn">
                        Cancel
                    </Link>
                    <button className="btn primary add" onClick={this.validateForm}>Submit</button>
                </div>
            </div>
        )
    }
}

CollectionForm.propTypes = {
    submitButton: PropTypes.string.isRequired,
    cancelLink: PropTypes.string.isRequired,
    collection: PropTypes.shape({
        name: PropTypes.string.isRequired,
        description: PropTypes.string.isRequired,
        dateCreated: PropTypes.string.isRequired,
        creator: PropTypes.string.isRequired
    }).isRequired,
    collectionDidSave: PropTypes.func.isRequired,
    user: PropTypes.shape({
        id: PropTypes.string.isRequired
    }).isRequired,
    api: PropTypes.shape({
        save: PropTypes.func.isRequired
    }).isRequired
};

export default CollectionForm;
