import React from 'react';
import superagent from 'superagent';
import { fromUnixTime } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';

import {
    Accordion,
    Segment,
    Header,
    Image,
    Icon,
    Button,
    Table,
    Form,
    Label,
    Modal } from 'semantic-ui-react'

import { DEFAULT_TIMEZONE } from '../../CloudApi/Constants.js';

const MAX_BAN_REASON_LENGTH = 10;

export default class AccountBans extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showBanDialog: false,
            showUnbanDialog: false,
            disableCheckText: "",
            loading: false,

            dialogMessage: ""
        };
    }

    async componentDidMount() {
    }

    onUpdateDialogMessage(event, {name, value}) {
        event.preventDefault();
        this.setState({dialogMessage: value});
    }

    // Ban account dialog
    onBan(e) {
        e.preventDefault();
        this.setState({showBanDialog: true, dialogMessage: ""});
    }

    closeBanModal(e) {
        this.setState({showBanDialog: false});
    }

    async onConfirmBan(e) {
        e.preventDefault();
        if (this.state.dialogMessage && this.state.dialogMessage.length >= MAX_BAN_REASON_LENGTH) {
            this.setState({ loading: true });

            try {
                const disconnectResult = await superagent.get(`/cloud/admin/account/${this.props.account.id}/disconnect`).accept('json');
                console.log("Disconnected...");
            } catch (e) {
                console.log(e);
            }

            const payload = {
                message: this.state.dialogMessage
            };

            try {
                const banResult = await superagent.put(`/api/admin/account/${this.props.account.id}/ban`).accept('json').send(payload);
            } catch (e) {
                console.log(e);
            }

            window.location.href = `/account/${this.props.account.id}`;
        }
        this.setState({showBanDialog: false, loading: false});
    }

    // Unban account dialog
    onUnban(e) {
        e.preventDefault();
        this.setState({showUnbanDialog: true, dialogMessage: ""})
    }

    closeUnbanModal(e) {
        this.setState({showUnbanDialog: false});
    }

    async onConfirmUnban(e) {
        e.preventDefault();
        this.setState({ loading: true });

        const payload = {
            message: this.state.dialogMessage
        };

        try {
            const result = await superagent.put(`/api/admin/account/${this.props.account.id}/unban`).accept('json').send(payload);
        } catch (e) {
            console.log(e);
        }

        window.location.href = `/account/${this.props.account.id}`;
    }

    render() {
        if (this.props.account) {
            let verificationControl = this.props.account.isVerified ? (
                <Label color="green">YES</Label>
            ) : (
                <Label>Not verified</Label>
            );

            let accountStatus = this.props.account.status == "Banned" ? (
                <div>
                    <Label color="red">Banned</Label>
                </div>
            ) : (
                <Label color="green">OK</Label>
            )

            let bannedInfo = this.props.account.status == "Banned" ? (
                <div>
                    <Segment inverted color="red">
                        This account has been banned
                    </Segment>
                    <Table compact celled definition>
                        <Table.Body>
                            <Table.Row>
                                <Table.HeaderCell width={4}>Account Status</Table.HeaderCell>
                                <Table.Cell>
                                    {accountStatus}
                                </Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.HeaderCell width={4}>Unban:</Table.HeaderCell>
                                <Table.Cell>
                                    <Button color="green" onClick={this.onUnban.bind(this)}><Icon name='checkmark' size="small" />Unban this account</Button>
                                </Table.Cell>
                            </Table.Row>
                        </Table.Body>
                    </Table>
                </div>
            ) : (
                <Table compact celled definition>
                    <Table.Body>
                        <Table.Row>
                            <Table.HeaderCell width={4}>Account Status</Table.HeaderCell>
                            <Table.Cell>
                                {accountStatus}
                            </Table.Cell>
                        </Table.Row>
                        <Table.Row>
                            <Table.HeaderCell width={4}>Ban Account</Table.HeaderCell>
                            <Table.Cell>
                                <Button color="red" onClick={this.onBan.bind(this)}><Icon name='ban' size="small" />Ban This Account</Button>
                            </Table.Cell>
                        </Table.Row>
                    </Table.Body>
                </Table>
            );

            let banHistory = this.props.account.banHistory.length > 0 ? (
                <Table celled striped compact>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={1} collapsing>Date</Table.HeaderCell>
                            <Table.HeaderCell width={2} collapsing>Status change to</Table.HeaderCell>
                            <Table.HeaderCell width={3} collapsing>Note</Table.HeaderCell>
                            <Table.HeaderCell width={2} collapsing>Created By</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {this.props.account.banHistory.map(item => {
                            return (
                            <Table.Row>
                                <Table.Cell width={1} collapsing>
                                    {item.createdAt && formatInTimeZone(fromUnixTime(item.createdAt), DEFAULT_TIMEZONE, 'PPPp z')}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {item.newStatus}
                                </Table.Cell>
                                <Table.Cell width={3}>
                                    {item.message}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    <a href={`/account/${item.moderatorBigscreenAccountId}`}>{item.moderatorBigscreenAccountId}</a>
                                </Table.Cell>
                            </Table.Row>
                            )
                        })}
                    </Table.Body>
                </Table>
            ) : (
                <Segment inverted color="green">
                    This account has never been banned 😊😊😊
                </Segment>
            );

            return (
                <div>
                    <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                        onClose={this.closeBanModal.bind(this)}
                        open={this.state.showBanDialog}>
                        <Header icon='user' content='Ban Account' />
                        <Modal.Content>{
                            (this.props.account) &&
                            <p>Enter a reason to ban the account {this.props.account.username}:</p>
                        }
                        <Form.Input fluid size="medium" name="dialogMessage" value={this.state.dialogMessage} onChange={this.onUpdateDialogMessage.bind(this)} />
                        </Modal.Content>
                        <Modal.Actions>
                            <Button color='red' loading={this.state.loading} disabled={this.state.dialogMessage === null || this.state.dialogMessage.length < MAX_BAN_REASON_LENGTH} onClick={this.onConfirmBan.bind(this)}>
                                <Icon name='checkmark' />Yes, ban `em!
                            </Button>
                        </Modal.Actions>
                    </Modal>

                    <Modal dimmer="inverted" loading={this.state.loading}  closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                        onClose={this.closeUnbanModal.bind(this)}
                        open={this.state.showUnbanDialog}>
                        <Header icon='user' content='Unban Account' />
                        <Modal.Content>{
                            (this.props.account) &&
                            <p>Why do you want to unban {this.props.account.username}?</p>
                        }
                        <Form.Input fluid size="medium" name="dialogMessage" value={this.state.dialogMessage} onChange={this.onUpdateDialogMessage.bind(this)} />

                        </Modal.Content>
                        <Modal.Actions>
                            <Button color='green' loading={this.state.loading}  onClick={this.onConfirmUnban.bind(this)}>
                                <Icon name='checkmark' />Yes, unban `em!
                            </Button>
                        </Modal.Actions>
                    </Modal>

                    <div>
                        {this.props.account.isStaff && <Segment inverted color="blue">
                            This is a Bigscreen Staff Account
                        </Segment>}

                        <Header as="h2">Bans</Header>

                        {bannedInfo}

                        <Header as="h2">Ban History</Header>

                        {banHistory}
                    </div>
                </div>
            );
        }
    }
}
