import PropTypes from 'prop-types';
import React from 'react';
import { Promise } from 'rsvp';
import { i18n } from 'lib/i18n';
import notify from 'services/notify';
import Metrika from 'lib/metrika';

import OrgProfileActions from 'actions/OrgProfile';
import ModalActions from 'actions/Modal';

import FilePicker from 'ui/FilePicker';
import Icon from 'ui/Icon';
import Tip from 'ui/Tip';

import DEFAULT_LOGO from '../../../../static/i/yandex-connect.png';

const MAX_FILE_SIZE = 7; // megabytes
const MB = 1024 * 1024;

const ACCEPTED_FILE_TYPES = [
    'jpg', 'jpeg', 'png', 'gif', 'bmp',
];

// соотношение сторон: отношение ширины к высоте
const MAX_RATIO = 3; // по макетам макс размеры - 124х44 (2.82:1)
const MIN_RATIO = 1; // мин размеры - 44х44
// линейные размеры
const MIN_SIZE = 100; // каждая из сторон не меньше 44х2 для ретины
const MAX_SIZE = 1024;

const LIMITATIONS = {
    min_size: MIN_SIZE,
    max_size: MAX_SIZE,
    min_ratio: MIN_RATIO,
    max_ratio: MAX_RATIO,
    max_file_size: MAX_FILE_SIZE,
    file_types: ACCEPTED_FILE_TYPES.map(type => `*.${type}`).join(', '),
};

const Logo = React.createClass({

    _validate(data) {
        return new Promise(resolve => {
            const image = new Image();

            image.onload = () => {
                if (!image.width || !image.height) {
                    return resolve('invalid_image_size');
                }
                if (Math.min(image.width, image.height) < MIN_SIZE) {
                    return resolve('image_too_small');
                }
                if (Math.max(image.width, image.height) > MAX_SIZE) {
                    return resolve('image_too_big');
                }
                const ratio = image.width / image.height;

                if (ratio < MIN_RATIO) {
                    return resolve('image_too_narrow');
                }
                if (ratio > MAX_RATIO) {
                    return resolve('image_too_wide');
                }
                resolve();
            };
            image.onerror = () => {
                resolve('failed_to_load_image');
            };
            image.src = data.logo_file;
        });
    },

    _handleError(error) {
        if (error) {
            notify(i18n(`logo.error.${error}`, LIMITATIONS), 'error');

            return false;
        }

        return true;
    },

    _handleRead(event) {
        const data = {
            logo_file: event.target.result,
        };

        Metrika.send('Профиль организации', 'Смена логотипа', 'Сохранить');

        return this._validate(data)
            .then(this._handleError)
            .then(isImageValid => {
                if (isImageValid) {
                    OrgProfileActions.setLogo(data, this.props.organization.getId())
                        .then(() => {
                            Metrika.send('Профиль организации', 'Смена логотипа', 'Сохранён');
                            notify(i18n('common.status.done'), 'success');
                            OrgProfileActions.fetchLogo();
                        });
                }
            });
    },

    _handlePick(files) {
        let error;

        if (files) {
            const selectedFile = files[0];

            if (selectedFile && selectedFile.size > MAX_FILE_SIZE * MB) {
                error = 'file_too_large';
            }
        }

        return this._handleError(error);
    },

    _handleRemove() {
        const { organization } = this.props;

        Metrika.send('Профиль организации', 'Удаление логотипа', 'Удалить');

        ModalActions.confirm({
            title: i18n('logo.confirm_logo_removal.message'),
            onConfirm: () => {
                OrgProfileActions.removeLogo(organization.getId())
                    .then(() => {
                        Metrika.send('Профиль организации', 'Удаление логотипа', 'Удалён');
                        notify(i18n('common.status.done'), 'success');
                        OrgProfileActions.fetchLogo();
                    });
            },
            confirmButtonText: i18n('logo.confirm_logo_removal.confirm'),
        });
    },

    render() {
        const logoUrl = this.props.organization.getLogoUrl();
        const imageUrl = logoUrl || DEFAULT_LOGO;
        const component = {};

        if (logoUrl) {
            component.removeLogo = (
                <div className="org-profile-logo__remove">
                    <span className="action" onClick={this._handleRemove}>
                        {i18n('logo.remove_logo')}
                    </span>
                </div>
            );
        }

        if (this.props.editable) {
            component.options = (
                <div className="org-profile-logo__options">
                    <div className="org-profile-logo__add">
                        <FilePicker
                            accept={ACCEPTED_FILE_TYPES.map(type => `image/${type}`).join(', ')}
                            onPick={this._handlePick}
                            onRead={this._handleRead}
                        >
                            <span className="action">{i18n('logo.change_logo')}</span>
                        </FilePicker>
                        <div className="org-profile-logo__tip">
                            <Icon type="grey-question-mark" />
                            <Tip text={i18n('logo.description', LIMITATIONS)} theme="light" />
                        </div>
                    </div>
                    {component.removeLogo}
                </div>
            );
        }

        return (
            <div className="org-profile-logo">
                <div className="org-profile-logo__image-container">
                    <img className="org-profile-logo__image" src={imageUrl} />
                </div>
                {component.options}
            </div>
        );
    },

});

Logo.propTypes = {
    organization: PropTypes.object,
};

Logo.defaultProps = {
    editable: false,
};

export default Logo;
