import { Fragment, useState, useRef } from 'react';

import { me, updateAvatar } from '../api';

import Button from './Button';
import Icon from './Icon';
import UploadButton from './UploadButton';
import Avatar from './Avatar';
import { useVisitor } from './VisitorContext';
import { Helmet } from 'react-helmet';

/**
 * @param {{ onChange: Function }} props
 */
function ChangeAvatarForm({ onChange }) {
    const [visitor] = useVisitor();
    const [avatar, setAvatar] = useState('');
    const [preview, setPreview] = useState();
    const avatarInput = useRef();
    let avatarChanged = (newAvatar) => {
        setAvatar(newAvatar);
        setPreview('');
        if (newAvatar) {
            let reader = new FileReader();
            reader.onloadend = (preview) => {
                setPreview(preview.target.result);
            };
            reader.readAsDataURL(avatarInput.current.files[0]);
        }
    };
    let previewUser = { ...visitor, uname: '<preview>' };
    if (preview) {
        previewUser = { ...visitor, avatar: preview, uname: '<preview>' };
    }
    let onSubmitAvatar = (event) => {
        if (event.preventDefault) {
            event.preventDefault();
        }
        updateAvatar(avatarInput.current.files[0]).then(() => {
            avatarChanged('');
            me().then(visitor => {
                onChange(visitor);
            }).catch(console.error);
        }).catch(console.error);
    };
    return (
        <form>
            <small>Recommendations: PNG, 96x96, &lt;50Kb. Also, JPG and GIF supported.</small>
            <UploadButton inputRef={avatarInput}
                value={avatar} onChange={avatarChanged} />
            <Avatar user={visitor} />
            <Avatar user={previewUser} />
            <Button onClick={onSubmitAvatar}>Update</Button>
        </form>
    );
}

/**
 * @param {{ onChange: Function }} props
 */
export default function Settings({ onChange }) {

    const [visitor] = useVisitor();

    let passwordChanged = () => {
        console.log('password changed');
    };
    let onSubmitPassword = (event) => {
        if (event.preventDefault) {
            event.preventDefault();
        }
        console.log('password update');
    };
    let emailChanged = () => {
        console.log('email update');
    };
    let disableTelegram = () => {
        console.log('telegram disable');
    };
    let disableFacebook = (event) => {
        if (event.preventDefault) {
            event.preventDefault();
        }
        console.log('facebook disable');
    };
    let enableFacebook = (event) => {
        if (event.preventDefault) {
            event.preventDefault();
        }
        console.log('facebook enable');
    };
    let disableTwitter = () => {
        console.log('twitter disable');
    };
    let deleteJid = () => {
        // TODO
    };
    let addEmail = () => {
        // TODO
    };
    let deleteEmail = () => {
        // TODO
    };
    return (
        <div className="msg-cont">
            <Helmet>
                <title>Settings</title>
            </Helmet>
            <fieldset>
                <legend><Icon name="ei-user" size="m" />Changing your avatar</legend>
                <ChangeAvatarForm onChange={onChange} />
            </fieldset>
            <fieldset>
                <legend><Icon name="ei-unlock" size="m" />Changing your password</legend>
                <form>
                    <p>Change password: <input type="password" name="password" size={8}
                        onChange={passwordChanged} />
                        <Button onClick={onSubmitPassword}>Update</Button><br />
                        <i>(max. length - 16 symbols)</i></p>
                </form>
            </fieldset>
            <fieldset>
                <legend><Icon name="ei-sc-telegram" size="m" />Telegram</legend>
                {visitor.telegramName ? (
                    <form>
                        <div>Telegram: <b> {visitor.telegramName} </b> &mdash;
                                <Button onClick={disableTelegram}>Disable</Button>
                        </div>
                    </form>
                ) : (
                        <p>To connect Telegram account: send any text message to <a href="https://telegram.me/Juick_bot">@Juick_bot</a>
                        </p>
                    )}
            </fieldset>
            {
                visitor.jids && (
                    <form>
                        <fieldset>
                            <legend>XMPP accounts
                                </legend>
                            <p>Your accounts:</p>
                            <p>
                                {
                                    visitor.jids.map(jid =>
                                        <Fragment key={jid}>
                                            <label><input type="radio" name="delete" value={jid} />{jid}</label><br />
                                        </Fragment>
                                    )
                                }
                            </p>
                            {
                                visitor.jids && visitor.jids.length > 1 &&
                                <p><Button onClick={deleteJid}>Delete</Button></p>
                            }
                            <p>To add new jabber account: send any text message to <span><a href="xmpp:juick@juick.com?message;body=login">juick@juick.com</a></span>
                            </p>
                        </fieldset>
                    </form>
                )}
            <fieldset>
                <legend><Icon name="ei-envelope" size="m" />E-mail</legend>
                <form>
                    <p>Add account:<br />
                        <input type="text" name="account" />
                        <input type="hidden" name="page" value="email-add" />
                        <Button onClick={addEmail}>Add</Button>
                    </p>
                </form>
                <form>
                    <p>Your accounts:</p>
                    <p>
                        {
                            visitor.emails ? visitor.emails.map(email =>
                                <Fragment key={email}>
                                    <label>
                                        <input type="radio" name="account" value={email} />{email}
                                    </label>
                                    <br />
                                </Fragment>
                            ) : '-'
                        }
                    </p>
                    {
                        visitor.emails && visitor.emails.length > 1 &&
                        <Button onClick={deleteEmail}>Delete</Button>
                    }
                </form>
                {
                    visitor.emails &&
                    <>
                        {/** email_off */}
                        <form>
                            You can receive notifications to email:<br />
                            Sent to <select name="account" value={visitor.activeEmail || 'Disabled'} onChange={emailChanged}>
                                <option value="">Disabled</option>
                                {
                                    visitor.emails.map(email =>
                                        <option key={email} value={email}>
                                            {email}
                                        </option>
                                    )
                                }
                            </select>
                        </form>
                        {/** /email_off */}
                        <p>&nbsp;</p>
                        <p>You can post to Juick via e-mail. Send your <u>plain text</u> messages to <a href="mailto:juick@juick.com">juick@juick.com</a>.
                        You can attach one photo or video file.</p>
                    </>
                }
            </fieldset>
            <fieldset>
                <legend><Icon name="ei-sc-facebook" size="m" />Facebook</legend>
                {
                    visitor.facebookStatus && visitor.facebookStatus.connected ? (
                        visitor.facebookStatus.crosspostEnabled ?
                            <form>
                                <div>
                                    Facebook: <b>Enabled</b>&mdash;
                                    <Button onClick={disableFacebook}>Disable</Button>
                                </div>
                            </form>
                            :
                            <form>
                                <div>
                                    Facebook: <b>Disabled</b>&mdash;
                                    <Button onClick={enableFacebook}>Enable</Button>
                                </div>
                            </form>
                    ) : (
                            <p>Cross-posting to Facebook:
                                <a href="/_fblogin">
                                    <img src="//static.juick.com/facebook-connect.png" alt="Connect to Facebook" />
                                </a>
                            </p>
                        )}
            </fieldset>
            <fieldset>
                <legend><Icon name="ei-sc-twitter" size="m" />Twitter</legend>
                {visitor.twitterName ?
                    <form action="/settings" method="post">
                        <div>Twitter: <b>{visitor.twitterName}</b>&mdash;
            <input type="hidden" name="page" value="twitter-del" />
                            <Button onClick={disableTwitter}>Disable</Button>
                        </div>
                    </form>
                    :
                    <p>Cross-posting to Twitter: <a href="/_twitter"><img src="//static.juick.com/twitter-connect.png"
                        alt="Connect to Twitter" /></a></p>
                }
            </fieldset>

        </div>
    );
}