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

import { Segment, Header, Icon, Button, Table, Label, Modal, Message } from 'semantic-ui-react'
import { DEFAULT_TIMEZONE } from '../../CloudApi/Constants.js';

export default class AccountIPs extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            deviceHistory: [],
            showBanIPDialog: false,
            pendingBanIP: null,
        };
    }

    async componentDidMount() {
        return this.reload();
    }

    async reload() {
        try {
            this.setState({deviceHistory: null, loading: true});
            const deviceHistory = await superagent.get(`/api/admin/account/${this.props.account.id}/device_history`).accept('json');
            console.log(deviceHistory.body);

            this.setState({
                loading: false,
                deviceHistory: deviceHistory.body
            });
        } catch (e) {
            console.log(e);
            this.setState({
                loading: false,
                deviceHistory: null
            });
        }
    }

    // Ban IP Dialog
    onBanIP(pendingBanIP, e) {
        e.preventDefault();
        this.setState({showBanIPDialog: true, pendingBanIP });
    }

    async onRemoveBannedIP(ip, e) {
        e.preventDefault();
        try {
            const result = await superagent.put(`/api/admin/ip/${ip}`).accept('json').send({
                status: "FullAccess"
            });
            return this.reload();
        } catch (e) {
            console.log(e);
        }
    }

    closeBanIPModal(e) {
        this.setState({showBanIPDialog: false, pendingBanIP: null });
    }

    async onConfirmBanIP(e) {
        e.preventDefault();

        try {
            const result = await superagent.put(`/api/admin/ip/${this.state.pendingBanIP}`).accept('json').send({
                status: "BannedFromEverything"
            });
            this.setState({ showBanIPDialog: false, pendingBanIP: null });
            return this.reload();
        } catch (e) {
            this.setState({ showBanIPDialog: false, pendingBanIP: null });
            console.log(e);
        }
    }

    render() {
        if (this.state.loading) {
            return (
                <Segment loading={true}>Loading...</Segment>
            )
        }

        if (this.state.deviceHistory == null || this.state.deviceHistory.ips == null || this.state.deviceHistory.ips.length == 0) {
            return (
                <Segment>No IP list for this account. They've likely not logged in for a while.</Segment>
            )
        }

        // Sort by timestamp
        let sortedIPList = _.orderBy(this.state.deviceHistory.ips, ["date._seconds"], ["desc"]);

        // remove nulls
        sortedIPList = sortedIPList.filter(x => !!x);

        return (
            <div>
                <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                    onClose={this.closeBanIPModal.bind(this)}
                    open={this.state.showBanIPDialog}>
                    <Header icon='user' content='Ban IP Address' />
                    <Modal.Content>
                        {
                            (this.props.account.status == "Ok") &&
                            <Message negative>
                                <Message.Header>Ban the user's account first!</Message.Header>
                                <Message.Content>
                                    Banning the account will kick the user out of public rooms.
                                </Message.Content>
                            </Message>
                        }

                        {
                            (this.props.account) &&
                            <p>Are you sure you want to ban the ip address {this.state.pendingBanIP}?</p>
                        }
                        <Message color="orange">
                            <Message.Header>Hey!! This is a serious action!</Message.Header>
                            <Message.Content>
                                Make sure the user's behavior justifies this before you confirm the ban.
                            </Message.Content>
                        </Message>
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='red' active={this.props.account.status == "Banned"} onClick={this.onConfirmBanIP.bind(this)}>
                            <Icon name='checkmark' />Yes, get 'em outta here!!
                        </Button>
                    </Modal.Actions>
                </Modal>
                <Table celled>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={2}>IP Address</Table.HeaderCell>
                            <Table.HeaderCell width={2}>Status</Table.HeaderCell>
                            <Table.HeaderCell width={2}>Last Date</Table.HeaderCell>
                            <Table.HeaderCell>Device ID</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {sortedIPList.map(ipInfo => {
                            let dateString = "(n/a)";
                            if (ipInfo.date) {
                                if (ipInfo.date._seconds) {
                                    dateString = formatInTimeZone(fromUnixTime(ipInfo.date._seconds), DEFAULT_TIMEZONE, 'PPPp z');
                                } else if (_.isDate(ipInfo.date)) {
                                    dateString = formatInTimeZone(new Date(ipInfo.date), DEFAULT_TIMEZONE, 'PPPp z');
                                }
                            }

                            let statusLabelColor = (ipInfo.status === "FullAccess") ? "green" : "red";
                            return (
                            <Table.Row color="red">
                                <Table.Cell width={2}>
                                    <Label color="black" basic>{ipInfo.ip}</Label>
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    <Label color={statusLabelColor}>{ipInfo.status}</Label>
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {dateString}
                                </Table.Cell>
                                <Table.Cell>
                                    {
                                        (ipInfo.status === "FullAccess") ?
                                        <Button color="red" onClick={this.onBanIP.bind(this, ipInfo.ip)}><Icon name='ban' size="small" />Ban IP Address</Button> :
                                        <Button color="black" onClick={this.onRemoveBannedIP.bind(this, ipInfo.ip)}><Icon name='ban' size="small" />Remove IP Ban</Button>
                                    }

                                </Table.Cell>
                            </Table.Row>
                            )
                        })}

                    </Table.Body>
                </Table>
            </div>
        );
    }
}
