import React from "react";
import superagent from "superagent";

import AccountsWrapper from "./AccountsWrapper.jsx";
import AccountIPManager from "./Components/AccountIPManager.jsx";
import AccountAccessPolicyManager from "./Components/AccountAccessPolicyManager.jsx";

import {
    Segment,
    Header,
    Button,
    Form,
    Message,
    Divider } from "semantic-ui-react"

class AccountOnboarding extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: "",
            email: "",
            loading: false,
            error: null,
            success: false,
            createdAccount: null
        };
    }

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

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

        // Validation
        if (!this.state.username || this.state.username.trim() === "") {
            this.setState({ error: "Username is required" });
            return;
        }

        if (!this.state.email || this.state.email.trim() === "") {
            this.setState({ error: "Email is required" });
            return;
        }

        this.setState({ loading: true, error: null });

        try {
            const payload = {
                username: this.state.username,
                email: this.state.email
            };

            const result = await superagent.post('/api/admin/onboarding/account')
                .accept('json')
                .send(payload);

            console.log("Account created:", result.body);

            this.setState({
                loading: false,
                success: true,
                createdAccount: result.body,
                error: null
            });

        } catch (e) {
            console.error("Error creating account:", e);
            let errorMessage = "Failed to create account";

            if (e.response && e.response.body && e.response.body.error) {
                errorMessage = e.response.body.error;
            } else if (e.message) {
                errorMessage = e.message;
            }

            this.setState({
                loading: false,
                error: errorMessage,
                success: false
            });
        }
    }

    async reloadAccount() {
        if (!this.state.createdAccount || !this.state.createdAccount.id) {
            return;
        }

        try {
            const result = await superagent.get(`/api/admin/account/${this.state.createdAccount.id}`).accept('json');
            this.setState({ createdAccount: result.body });
        } catch (e) {
            console.error("Error reloading account:", e);
        }
    }

    onCreateAnother(e) {
        e.preventDefault();
        this.setState({
            username: "",
            email: "",
            success: false,
            createdAccount: null,
            error: null
        });
    }

    render() {
        return (
            <div>
                <AccountsWrapper title="Account Onboarding" menuItems={[]} loading={this.state.loading}>
                    {!this.state.success && (
                        <div>
                            <Header as="h3">
                                <Header.Content>Create a New Account
                                    <Header.Subheader>Enter username and email address to get started</Header.Subheader>
                                </Header.Content>
                            </Header>

                            {this.state.error && (
                                <Message negative>
                                    <Message.Header>Error</Message.Header>
                                    <p>{this.state.error}</p>
                                </Message>
                            )}

                            <Segment>
                                <Form size="large" onSubmit={this.onCreateAccount.bind(this)}>
                                    <Form.Input
                                        required
                                        icon="user"
                                        label="Username"
                                        placeholder="Enter username"
                                        value={this.state.username}
                                        name="username"
                                        onChange={this.onChange.bind(this)}
                                        disabled={this.state.loading}
                                    />
                                    <Form.Input
                                        required
                                        icon="mail"
                                        label="Email"
                                        placeholder="Enter email address"
                                        value={this.state.email}
                                        name="email"
                                        type="email"
                                        onChange={this.onChange.bind(this)}
                                        disabled={this.state.loading}
                                    />
                                    <Button
                                        size="large"
                                        color="green"
                                        type="submit"
                                        disabled={this.state.loading || !this.state.username || !this.state.email}
                                        loading={this.state.loading}
                                    >
                                        Create Account
                                    </Button>
                                </Form>
                            </Segment>
                        </div>
                    )}

                    {this.state.success && this.state.createdAccount && (
                        <div>
                            <Message positive>
                                <Message.Header>Account Created Successfully!</Message.Header>
                                <p>Account ID: <strong>{this.state.createdAccount.id}</strong></p>
                                <p>Username: <strong>{this.state.createdAccount.username}</strong></p>
                                <p>Email: <strong>{this.state.createdAccount.email}</strong></p>
                            </Message>

                            <Divider />

                            <Segment>
                                <AccountAccessPolicyManager
                                    accountId={this.state.createdAccount.id}
                                    accessPolicies={this.state.createdAccount.accessPolicies || []}
                                    onUpdate={this.reloadAccount.bind(this)}
                                />
                            </Segment>

                            <Divider />

                            <Segment>
                                <AccountIPManager
                                    accountId={this.state.createdAccount.id}
                                    accountStatus={this.state.createdAccount.status}
                                />
                            </Segment>

                            <Divider />

                            <Button color="blue" onClick={this.onCreateAnother.bind(this)}>
                                Create Another Account
                            </Button>
                            <Button color="black" as="a" href={`/account/${this.state.createdAccount.id}`}>
                                View Full Account Details
                            </Button>
                        </div>
                    )}
                </AccountsWrapper>
            </div>
        );
    }
}

export default AccountOnboarding;
