import env from "/_/code/env.js"
import server from "/_/code/bridge/serverFunctions.js"
import "../../components/LoadingCircleSmall.js"

class Settings extends Shadow {
    stripeDetails = null

    handleConnectStripe = () => {
        const state = btoa(JSON.stringify({
            returnTo: window.location.href,
            networkId: global.currentNetwork.id
        }));

        const params = new URLSearchParams({
            response_type: 'code',
            client_id: env.client_id,
            scope: 'read_write',
            redirect_uri: `${env.baseURL}/stripe/onboardingcomplete`,
            state,
        });

        window.location.href = `https://connect.stripe.com/oauth/authorize?${params}`;
    };

    render() {
        ZStack(() => {
            h1("Settings")
                .fontWeight("bold")
                .marginTop(4, pct)
                .marginLeft(5, pct)

            VStack(() => {
                HStack(() => {
                    p("Stripe Integration")

                    if(this.stripeDetails && this.stripeDetails.data.email) {
                        p("connected")
                    } else if(this.stripeDetails && this.stripeDetails.data.connected === false) {
                        button("Set up Stripe")
                            .maxWidth(10, em)
                            .onClick((done) => {
                                this.handleConnectStripe()
                            })
                    } else {
                        LoadingCircleSmall()
                    }
                })
                .gap(10, pct)
                .verticalAlign("center")
            })
            .gap(0.5, em)
            .paddingLeft(5, pct)
            .marginTop(4, em)
        })
    }

    async getStripeProfile() {
        this.stripeDetails = await server.getStripeProfile(global.currentNetwork.id)
        this.rerender()
    }

    connectedCallback() {
        this.getStripeProfile()
    }
}

register(Settings)