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

import EventsWrapper from './EventsWrapper.jsx';
import Messages from '../Util/Messages.jsx';

import { 
    Accordion,
    Segment,
    Dropdown,
    Grid,
    Header,
    Form,
    Image,
    Message,
    Icon,
    Button,
    Table, 
    Divider} from 'semantic-ui-react';

export default class TopicEditor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            topic: {
                id: null,
                name: "",
                title: "",
                description: ""
            }
        };
    }

    async componentDidMount() {
        if (this.props.match.params.topicId) {
            this.setState({ loading: true });
            const res = await superagent.get(`/api/admin/topic/${this.props.match.params.topicId}`).accept('json');
            this.setState({ topic: res.body, loading: false });
        }
    }

    async onSaveTopic() {
        try {
            this.setState({ loading: true });
            if (this.state.topic.id) {
                const res = await superagent.put(`/api/admin/topic`).send(this.state.topic);
                this.setState({ loading: false });
            } else {
                const res = await superagent.post(`/api/admin/topic`).send(this.state.topic);
                this.props.history.push({pathname: '/events/topics'});

                // HACK HACK HACK - reload the window to force express to refresh cookies.
                window.location.reload();
            }
        } catch (e) {
            if (e.response.status === 401) {
                this.setState({
                    loading: false,
                    messages: [{ msg: e.response.body.message }]
                });
            } else if (e.response.status === 422) {
                this.setState({
                    loading: false,
                    messages: e.response.body
                });
            } else {
                this.setState({
                    loading: false,
                    messages: [{msg: "Login failed!"}]
                })
            }
        }
    }
    
    async onChange(e, { name, value }) {
        const topic = this.state.topic;
        topic[name] = value;
        this.setState({ topic });
    }

    render() {
        if (!this.state.topic) {
            return <div />;
        }
        
        if (this.state.topic.id) {
            return (
                <EventsWrapper loading={this.state.loading}>
                    {(this.state.topic.id) && <Header as="h2">Edit Topic</Header>}
                    
                    <Form size='small' onSubmit={this.onSaveTopic.bind(this)}>
                        {(this.state.topic.id) && 
                        <Form.Group>
                            <Form.Input required label='id' value={this.state.topic.id} name="id" readOnly />
                        </Form.Group>}

                        <Form.Group widths="equal">
                            <Form.Input width={4} autoComplete="off" required label='Unique Name' value={this.state.topic.name} name="name" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group widths="equal">
                            <Form.Input autoComplete="off" required label='Title' value={this.state.topic.title} name="title" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group widths="equal">
                            <Form.Input autoComplete="off" required label='Description' value={this.state.topic.description} name="description" onChange={this.onChange.bind(this)} />
                        </Form.Group>
                        
                        <Segment basic>
                            {(this.state.topic.id) && <Form.Group><Button primary content='Save topic' type='submit' /></Form.Group>}
                        </Segment>
                    </Form>
                </EventsWrapper>
            )
        } else {
            return (
                <EventsWrapper loading={this.state.loading}>
                    
                    <Header as="h2">Create a topic</Header>

                    <Messages className="inverted" messages={this.state.messages} />

                    <Form size='small' onSubmit={this.onSaveTopic.bind(this)}>
                        <Form.Group>
                            <Form.Input width={4} autoComplete="off" required label='Unique Name' value={this.state.topic.name} name="name" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group>
                            <Form.Input width={8} autoComplete="off" required label='Title' value={this.state.topic.title} name="title" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group>
                            <Form.Input width={8} autoComplete="off" required label='Description' value={this.state.topic.description} name="description" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Form.Group><Button primary content='Create Topic' type='submit' /></Form.Group>
                    </Form>
                </EventsWrapper>
            );
        }
    }
}
