import React from 'react';
import block from 'bem-cn';
import { Attach, Icon } from 'lego-on-react';
import QuestionIcon from 'components/Icon/Question';
import TooltipBox from 'components/TooltipBox';
import getOrganization from 'lib2/getOrganization';
import fetchOrgLogo from 'lib2/fetchOrgLogo';
import notify from 'lib2/notify';
import directory from 'api2/directory';
import metrika from 'api2/metrika';
import { i18n } from 'i18n2';
import { AllowedFileTypes, Ratio, Dimensions, MAX_FILE_SIZE } from './config';
import validateFile from './validateFile';

const b = block('org-logo-picker');
const MB = 1024 * 1024;

const TipData = {
    min_size: Dimensions.MIN,
    max_size: Dimensions.MAX,
    min_ratio: Ratio.MIN,
    max_ratio: Ratio.MAX,
    max_file_size: MAX_FILE_SIZE,
    file_types: AllowedFileTypes.map(type => `*.${type}`).join(', '),
};

export default class OrgLogoPicker extends React.Component {
    constructor() {
        super();

        this._onFileChange = this._onFileChange.bind(this);
    }

    _onFileChange({ target: { files } }) {
        let file = files[0];

        if (!file) {
            return;
        }

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

        if (file.size > MAX_FILE_SIZE * MB) {
            return notify(i18n('logo.error.file_too_large', TipData), 'error');
        }

        validateFile(file)
            .then(error => {
                if (error) {
                    return notify(i18n(`logo.error.${error}`, TipData), 'error');
                }

                let body = new FormData();

                body.append('logo_file', file);

                return directory
                    .send('POST', `/v11/organizations/${getOrganization().id}/change-logo/`, { body })
                    .then(({ ok, body }) => {
                        metrika.send(
                            'Профиль организации',
                            'Смена логотипа',
                            ok ? 'Сохранён' : 'Ошибка при сохранении',
                        );

                        if (!ok) {
                            let message = i18n(`logo.error.${body.code}`, TipData) ||
                                i18n(`backend_errors.${body.code}`, TipData) ||
                                i18n('common.status.failed');

                            notify(message, 'error');

                            return;
                        }

                        notify(i18n('common.status.done'), 'success');

                        return fetchOrgLogo();
                    });
            });
    }

    render() {
        let { cls, text } = this.props;

        return (
            <span className={b({}).mix(cls)}>
                <Attach
                    cls={b('attach')}
                    theme="link"
                    view="default"
                    size="m"
                    accept={AllowedFileTypes.map(type => `.${type}`).join(',')}
                    onChange={this._onFileChange}
                >
                    {text}
                </Attach>
                <TooltipBox
                    htmlTip={i18n('logo.description', TipData)}
                    theme="normal"
                    to="right"
                    size="s"
                >
                    <Icon
                        cls={b('tip-icon')}
                        glyph="yes"
                    >
                        <QuestionIcon />
                    </Icon>
                </TooltipBox>
            </span>
        );
    }
}
