import React from 'react';
import superagent from 'superagent';
import { Link } from 'react-router-dom';
import { Container, Header, Segment, Table, Button, Icon, Label, Message, Loader, Checkbox } from 'semantic-ui-react';

/**
 * Developer portal home.
 *
 * Lists OAuth clients. Admin and SuperUser both see every client; only the
 * owner (or a SuperUser) can mutate a given row. The `canManage` flag the
 * backend returns per row drives the lock icon next to rows the viewer
 * can only read. SuperUsers get an extra toggle to include soft-deleted
 * clients in the list.
 */
export default class DevHome extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            clients: [],
            viewerIsSuperUser: false,
            includeDeleted: false,
            error: null
        };
    }

    async componentDidMount() {
        await this.fetchClients();
    }

    async fetchClients() {
        this.setState({ loading: true, error: null });
        try {
            const qs = this.state.includeDeleted ? '?includeDeleted=true' : '';
            const res = await superagent.get(`/api/admin/oauth/clients${qs}`).accept('json');
            this.setState({
                clients: res.body.clients || [],
                viewerIsSuperUser: !!res.body.viewerIsSuperUser,
                loading: false
            });
        } catch (e) {
            this.setState({ error: e.response?.body?.message || e.message, loading: false });
        }
    }

    async onToggleIncludeDeleted() {
        this.setState({ includeDeleted: !this.state.includeDeleted }, () => this.fetchClients());
    }

    renderClientRow(client) {
        const disabled = client.disabledAt !== null && client.disabledAt !== undefined;
        const deleted = client.deletedAt !== null && client.deletedAt !== undefined;
        return (
            <Table.Row key={client.uniqueId} disabled={deleted}>
                <Table.Cell>
                    <Link to={`/developers/apps/${client.uniqueId}`}>
                        <strong>{client.name}</strong>
                    </Link>
                    {!client.canManage && (
                        <Icon
                            name="lock"
                            size="small"
                            style={{ marginLeft: 6, color: '#999' }}
                            title="Read-only — you are not the owner"
                        />
                    )}
                    {disabled && <Label color="red" size="mini" style={{ marginLeft: 8 }}>disabled</Label>}
                    {deleted && <Label color="grey" size="mini" style={{ marginLeft: 8 }}>deleted</Label>}
                </Table.Cell>
                <Table.Cell><code>{client.clientId}</code></Table.Cell>
                <Table.Cell style={{ fontSize: '0.9em' }}>
                    <code style={{ fontSize: '0.9em' }}>{client.ownerAccountId}</code>
                </Table.Cell>
                <Table.Cell>
                    {(client.allowedScopes || []).map(s => (
                        <Label key={s} size="mini" style={{ margin: 2 }}>{s}</Label>
                    ))}
                </Table.Cell>
                <Table.Cell>
                    {(client.serverIps || []).join(', ')}
                </Table.Cell>
                <Table.Cell>
                    {client.createdAt ? new Date(client.createdAt).toLocaleString() : ''}
                </Table.Cell>
            </Table.Row>
        );
    }

    render() {
        const { loading, clients, error, viewerIsSuperUser, includeDeleted } = this.state;

        return (
            <Container style={{ padding: '1em' }}>
                <Segment basic clearing>
                    <Header as="h1" floated="left">
                        <Icon name="code" />
                        <Header.Content>
                            Developer Portal
                            <Header.Subheader>OAuth clients registered with Bigscreen</Header.Subheader>
                        </Header.Content>
                    </Header>
                    <Button as={Link} to="/developers/new" primary floated="right" icon labelPosition="left">
                        <Icon name="plus" />
                        Register new client
                    </Button>
                </Segment>

                {viewerIsSuperUser && (
                    <Segment basic style={{ padding: '0 0 0.5em 0' }}>
                        <Checkbox
                            toggle
                            label="Include soft-deleted clients (SuperUser)"
                            checked={includeDeleted}
                            onChange={() => this.onToggleIncludeDeleted()}
                        />
                    </Segment>
                )}

                {error && <Message negative><Message.Header>Failed to load clients</Message.Header><p>{error}</p></Message>}

                {loading && <Loader active inline="centered">Loading…</Loader>}

                {!loading && clients.length === 0 && (
                    <Message info>
                        <Message.Header>No OAuth clients registered yet</Message.Header>
                        <p>Click "Register new client" above to create one. Remember: confidential clients only in v1, and each client must declare a whitelisted server IP.</p>
                    </Message>
                )}

                {!loading && clients.length > 0 && (
                    <Table selectable compact>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell>Name</Table.HeaderCell>
                                <Table.HeaderCell>Client ID</Table.HeaderCell>
                                <Table.HeaderCell>Owner</Table.HeaderCell>
                                <Table.HeaderCell>Allowed scopes</Table.HeaderCell>
                                <Table.HeaderCell>Server IPs</Table.HeaderCell>
                                <Table.HeaderCell>Created</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            {clients.map(c => this.renderClientRow(c))}
                        </Table.Body>
                    </Table>
                )}
            </Container>
        );
    }
}
