import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';
import UserStore from 'stores/Users';
import Link from 'ui/Link';

import './index.css';

function toUrl(url) {
    return !url || /^https?:\/\//.test(url) ? url : `http://${url}`;
}

const Contacts = React.createClass({

    _getList() {
        const { id, compact } = this.props;
        const user = UserStore.get(id);

        if (!user) {
            return null;
        }

        return compact ? user.getMinimalContacts() : user.getOrderedContacts();
    },

    render() {
        const contacts = this._getList();

        if (!contacts) {
            return null;
        }

        const items = contacts.map((item, index) => {
            const label = i18n(`user.contacts.${item.type}`) || _.capitalize(item.type);
            let link;

            item.value = item.value || '';

            switch (item.type) {
                case 'email':
                    item.url = Url.getEmail(item.value);
                    break;
                case 'site':
                    item.url = toUrl(item.value);
                    // item.value = item.value.replace(/^http:\/\//, '').replace(/\/$/, '');
                    break;
                case 'staff':
                    if (item.value) {
                        let url = new URL(item.value);

                        item.url = url.href;
                        item.value = url.pathname.split('/')[1];
                    }
                    break;
            }

            if (item.url) {
                link = (
                    <Link className="link" to={item.url} title={item.value} target="_blank">
                        {item.value}
                    </Link>
                );
            }

            return (
                <div className="list-item" key={`user-contact-${index}`}>
                    <div className="list-item__key" title={label}>
                        {label}:
                    </div>
                    <div className="list-item__value">
                        {link || item.value}
                    </div>
                </div>
            );
        });

        if (!items.length) {
            return null;
        }

        return (
            <div className="user-contacts list separated-subsection">
                {items}
            </div>
        );
    },

});

Contacts.propTypes = {
    id: PropTypes.string,
    compact: PropTypes.bool,
};

export default Contacts;
