import React from 'react';
import superagent from 'superagent';

import { Segment, Header, Icon, Button, Table, Label, Modal, Message, Form } from 'semantic-ui-react'
import ApiButtonModal from '../../CloudApi/ApiButtonModal.jsx';

export default class AccountIPManager extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            securityGroup: null,
            newIpAddress: ""
        };
    }

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

    async reload() {
        try {
            this.setState({securityGroup: null, loading: true});
            const result = await superagent.get(`/api/admin/account/${this.props.accountId}/security_groups`).accept('json');

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

    async onChange(e, { name, value }) {
        this.setState({ [name]: value })
    }

    stripCidrSuffix(cidrIp) {
        // Strip /32 for IPv4 or /128 for IPv6
        if (cidrIp.endsWith('/32') || cidrIp.endsWith('/128')) {
            return cidrIp.substring(0, cidrIp.lastIndexOf('/'));
        }
        return cidrIp;
    }

    async onAddIP() {
        try {
            const ipAddress = this.stripCidrSuffix(this.state.newIpAddress);
            const result = await superagent.put(`/api/admin/account/${this.props.accountId}/security_groups/${ipAddress}`).accept('json').send();
            console.log(result.body);
            this.setState({ newIpAddress: "" });
            await this.reload();
        } catch (e) {
            console.log(e);
        }
    }

    async onRemoveIP(ipRange) {
        try {
            const ipAddress = this.stripCidrSuffix(ipRange.CidrIp);
            const result = await superagent.delete(`/api/admin/account/${this.props.accountId}/security_groups/${ipAddress}`).accept('json').send();
            console.log(result.body);
            await this.reload();
        } catch (e) {
            console.log(e);
        }
    }

    getAccessType(ipPermission) {
        if (ipPermission.IpProtocol === 'tcp' && ipPermission.FromPort === 443 && ipPermission.ToPort === 443) {
            return 'Web Access';
        }
        if (ipPermission.FromPort && ipPermission.ToPort) {
            return `${ipPermission.IpProtocol} ports ${ipPermission.FromPort}-${ipPermission.ToPort}`;
        }
        return ipPermission.IpProtocol;
    }

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

        if (!this.state.securityGroup) {
            return (
                <Segment>No security group information available for this account.</Segment>
            )
        }

        const securityGroup = this.state.securityGroup;

        // Collect all IP ranges from all permissions
        const ipRanges = [];
        if (securityGroup.IpPermissions && securityGroup.IpPermissions.length > 0) {
            securityGroup.IpPermissions.forEach(permission => {
                if (permission.IpRanges && permission.IpRanges.length > 0) {
                    permission.IpRanges.forEach(ipRange => {
                        ipRanges.push({
                            ...ipRange,
                            permission: permission
                        });
                    });
                }
            });
        }

        return (
            <div>
                <Header as="h2">IP Addresses
                    <Header.Subheader>Allows HTTPS Access to Arda and Admin APIs</Header.Subheader>
                </Header>
                <Table celled striped compact>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell>IP Address</Table.HeaderCell>
                            <Table.HeaderCell>Access Type</Table.HeaderCell>
                            <Table.HeaderCell width={3} collapsing>Actions</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {ipRanges.length > 0 ? (
                            ipRanges.map((ipRange, index) => {
                                const accessType = this.getAccessType(ipRange.permission);
                                const displayIp = this.stripCidrSuffix(ipRange.CidrIp);
                                return (
                                    <Table.Row key={index}>
                                        <Table.Cell>
                                            <Label color="blue">{displayIp}</Label>
                                            {ipRange.Description && (
                                                <span style={{ marginLeft: '10px', color: 'grey' }}>
                                                    {ipRange.Description}
                                                </span>
                                            )}
                                        </Table.Cell>
                                        <Table.Cell>
                                            <Label>{accessType}</Label>
                                        </Table.Cell>
                                        <Table.Cell collapsing>
                                            <ApiButtonModal
                                                color="red"
                                                size="small"
                                                icon="trash"
                                                text="Remove"
                                                modalIcon="warning sign"
                                                modalButtonText="Yes, remove this IP address"
                                                onConfirm={() => this.onRemoveIP(ipRange)}>
                                                Are you sure you want to remove <strong>{displayIp}</strong> from this account's allowed IP addresses?
                                                <br /><br />
                                                <Message warning icon>
                                                    <Icon name="warning" />
                                                    <Message.Content>
                                                        <Message.Header>Warning</Message.Header>
                                                        This will immediately revoke access from this IP address.
                                                    </Message.Content>
                                                </Message>
                                            </ApiButtonModal>
                                        </Table.Cell>
                                    </Table.Row>
                                )
                            })
                        ) : (
                            <Table.Row>
                                <Table.Cell colSpan={3}>
                                    <Message info>No IP addresses configured for this account.</Message>
                                </Table.Cell>
                            </Table.Row>
                        )}
                        <Table.Row>
                            <Table.Cell colSpan={3}>
                                <ApiButtonModal
                                    color="green"
                                    size="small"
                                    icon="plus"
                                    text="Add IP"
                                    modalIcon="server"
                                    modalButtonText="Add IP Address"
                                    onConfirm={this.onAddIP.bind(this)}>
                                    <p>Add a new IP address to this account's security group.</p>
                                    <Form>
                                        <Form.Input
                                            required
                                            fluid
                                            label='IP Address'
                                            name="newIpAddress"
                                            placeholder="e.g., 192.168.1.1"
                                            value={this.state.newIpAddress}
                                            onChange={this.onChange.bind(this)}
                                        />
                                    </Form>
                                </ApiButtonModal>
                            </Table.Cell>
                        </Table.Row>
                    </Table.Body>
                </Table>
            </div>
        );
    }
}
