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

import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';

import { Container, Menu, Segment, Grid, Header, Image, Icon, Button, Form, Divider } from 'semantic-ui-react'

export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            loading: false
        };
    }
    
    onChange(e, { name, value }) {
        this.setState({ [name]: value })
    }

    getReturnToFromUrl() {
        // Plan 14 Phase B: /oauth/authorize redirects here with ?returnTo=…
        // so that after login the user lands back at the consent screen.
        try {
            const params = new URLSearchParams(window.location.search);
            return params.get('returnTo') || '';
        } catch (e) {
            return '';
        }
    }

    async onLogin(event) {
        event.preventDefault();
        let payload = {
            email: this.state.email,
            password: this.state.password,
            returnTo: this.getReturnToFromUrl()
        };

        this.setState({
            loading: true
        });

        try {
            const res = await superagent.post('/api/auth/login')
                .accept('json')
                .send(payload);
            // Server validates returnTo same-origin and echoes back the
            // sanitised value (or '/'). Trust the server's answer.
            const target = (res.body && res.body.returnTo) || '/';
            window.location.href = target;
        } catch (e) {
            this.setState({ error: e });
        }

        this.setState({
            loading: false
        });
    }

    render() {
        return (
            <Grid verticalAlign="middle" textAlign="center">
                <Grid.Column width={10}>
                    <Header as="h1">{this.props.title}</Header>
                    <BigApiErrorMessage error={this.state.error} />
                    <Segment secondary padded="very" textAlign="left" loading={this.state.loading}>
                        <Form size='huge' onSubmit={this.onLogin.bind(this)}>
                            <Form.Group widths='equal'>
                                <Form.Input icon="mail" required label='Email' placeholder='Email' 
                                    name="email" onChange={this.onChange.bind(this)} />
                            </Form.Group>
                            <Form.Group widths='equal'>
                                <Form.Input icon="lock" required label='Password' type='password' 
                                    name="password" onChange={this.onChange.bind(this)} />
                            </Form.Group>
                            <Segment basic textAlign="center">
                                <Button size='huge' primary icon='right arrow' labelPosition='right' content='Login' type='submit' />
                            </Segment>
                        </Form>
                    </Segment>
                </Grid.Column>
            </Grid>
        );
    }
}
