<template>
    <div class="new-method">
        <h2 class="mb-4 text-lg font-semibold text-center text-gray-300">
            {{ $t("Register.new_method") }}
        </h2>
        <div class="flex justify-center w-full max-w-md mx-auto contaianer">
            <FormKit
                type="radio"
                name="method"
                value="bank"
                :options="[
                    { label: $t('Register.bank_account'), value: 'bank' },
                    { label: $t('Register.card'), value: 'card' },
                ]"
                v-model="method"
                class="mx-2"
            />
        </div>
        <hr class="mb-4" />
        <!-- <p
            v-if="error"
            class="mt-3 text-lg font-medium text-center text-red-300"
        >
            {{ error }}
        </p> -->
        <div class="" v-show="method == 'bank'">
            <FormKit
                id="new_method"
                #default="{ state: { valid } }"
                :actions="false"
                name="new_method"
                type="form"
                @submit="createBankToken"
            >
                <FormKit
                    id="city"
                    v-model="bankData.account_number"
                    :label="$t('Register.account_number') + ' (IBAN)'"
                    required
                    type="text"
                    validation="required"
                    validation-label="Account Number"
                />
                <FormKit
                    id="city"
                    v-model="bankData.account_holder_name"
                    :label="$t('Register.holder_name')"
                    required
                    type="text"
                    validation="required"
                    validation-label="holder name"
                />
                <FormKit
                    id="city"
                    v-model="bankData.routing_number"
                    :label="$t('Register.routing_number')"
                    required
                    type="text"
                    validation="required|length:9,9"
                    validation-label="routing number"
                />
                <div class="flex items-center justify-between gap-2">
                    <FormKit
                        type="select"
                        v-model="bankData.country"
                        name="country"
                        label="Country of account"
                        :options="countries"
                    />
                    <FormKit
                        type="select"
                        v-model="bankData.currency"
                        name="currency"
                        label="currency of account"
                        :options="currencies"
                    />
                </div>
                <hr class="mb-5" />
                <div class="flex justify-center w-full">
                    <FormKit
                        type="radio"
                        name="account_holder_type"
                        :options="[
                            {
                                label: $t('Register.individual'),
                                value: 'individual',
                            },
                            { label: $t('Register.company'), value: 'company' },
                        ]"
                        v-model="bankData.account_holder_type"
                        class="mx-2"
                    />
                </div>

                <div class="flex items-center justify-center w-full">
                    <Button
                        size="full-sm"
                        type="submit"
                        :disabled="bankData.processing || !valid || loading"
                        :loading="bankData.processing || loading"
                        @click="submit"
                    >
                        {{ $t("Register.confirm") }}
                    </Button>
                </div>
                <div v-if="error" class="my-3 text-xs font-normal text-red-300">
                    {{ error }}
                </div>
            </FormKit>
            <!-- <form @submit="createBankToken" class="flex flex-col gap-y-2">
                <div>
                    <h4 class="mb-1 text-sm font-medium text-gray-300">
                        {{ $t("Register.account_type") }}
                    </h4>
                    <div class="flex space-x-4">
                        <div>
                            <input
                                type="radio"
                                id="individual"
                                value="individual"
                                v-model="bankData.account_holder_type"
                                class="mx-2"
                            />
                            <label for="individual">{{
                                $t("Register.individual")
                            }}</label>
                        </div>
                        <div>
                            <input
                                type="radio"
                                id="company"
                                value="company"
                                v-model="bankData.account_holder_type"
                                class="mx-2"
                            />
                            <label for="company">{{
                                $t("Register.company")
                            }}</label>
                        </div>
                    </div>
                </div>
                <div class="flex items-center w-full mt-5">
                    <button
                        class="border border-blue-300 rounded-full mx-auto text-blue-300 font-medium text-sm px-4 py-1.5"
                    >
                        {{ $t("Register.confirm") }}
                    </button>
                </div>
            </form> -->
        </div>
        <div v-show="method != 'bank'" class="mx-4">
            <section id="stripe-payment-form" ref="card"></section>
            <div class="flex items-center w-full mt-5">
                <div class="flex items-center justify-center w-full">
                    <Button
                        size="full-sm"
                        type="submit"
                        :disabled="loading"
                        :loading="loading"
                        @click="createCardToken"
                    >
                        {{ $t("Register.confirm") }}
                    </Button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { useForm } from "@inertiajs/inertia-vue3";

import { StripeElementCard } from "@vue-stripe/vue-stripe";
import { loadStripe } from "@stripe/stripe-js";
import currencies from "@/assets/currencies.json";
import countries from "@/assets/countries.json";
import Button from "@/Jetstream/Button";

export default {
    components: {
        StripeElementCard,
        Button,
    },
    data() {
        return {
            method: "bank",
            token: null,
            error: null,
            loading: false,
            bankData: useForm({
                currency: "USD",
                country: "US",
                routing_number: "",
                account_number: "",
                account_holder_name: "",
                account_holder_type: "individual",
            }),

            stripe: null,
            elements: null,
            paymentElement: null,
            appearance: {
                theme: "stripe",

                variables: {
                    colorPrimary: "#29419B",
                    colorBackground: "#ffffff",
                    colorText: "#222222",
                    colorDanger: "#F1416C",
                    fontFamily: "Inter, system-ui, -apple-system",
                    spacingUnit: "6px",
                    borderRadius: "8px",
                },
            },
            currencies: currencies.currencies,
            countries: countries.countries,
        };
    },
    methods: {
        createCardToken() {
            try {
                this.loading = true;
                this.stripe
                    .createToken(this.paymentElement)
                    .then((result) => {
                        if (result.token) {
                            let cardForm = useForm({
                                token: result.token,
                                type: "card",
                            });

                            cardForm.post("/u/billing", {
                                onSuccess: (res) => {
                                    this.$emit("close");
                                },
                                onError: (res) => {
                                    this.error = res.error.message;
                                },
                            });
                        } else {
                            this.$page.props.flash.error = result.error.message;
                            this.error = res.error.message;
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            } catch (error) {
                this.$page.props.flash.error =
                    "Something wrong please try again";
            }

            return true;
        },

        createBankToken: async function (e) {
            try {
                this.loading = true;
                return this.stripe
                    .createToken("bank_account", {
                        country: this.bankData.country,
                        currency: this.bankData.currency,
                        routing_number: this.bankData.routing_number,
                        account_number: this.bankData.account_number,
                        account_holder_name: this.bankData.account_holder_name,
                        account_holder_type: this.bankData.account_holder_type,
                    })
                    .then((res) => {
                        if (res.token) {
                            let cardForm = useForm({
                                token: res.token,
                                type: "bank_account",
                            });
                            cardForm.post("/u/billing", {
                                onSuccess: (res) => {
                                    this.$emit("close");
                                },
                            });
                        } else {
                            this.$page.props.flash.error = res.error.message;
                            this.error = res.error.message;
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            } catch (error) {
                this.$page.props.flash.error =
                    "Something wrong please try again";
            }
            e.preventDefault();
        },
        async initStripe() {
            this.stripe = await loadStripe(this.$page.props.stripe.key);
            this.elements = await this.stripe.elements({
                appearance: this.appearance,
            });
            this.createPaymentElement();
        },
        async createPaymentElement() {
            this.paymentElement = await this.elements.create("card");

            this.mountElement(this.paymentElement, "#stripe-payment-form");
        },
        mountElement(element, container) {
            element.mount(container);
        },
    },
    mounted() {
        this.initStripe();
    },
};
</script>

<style>
.new-method .formkit-options {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    gap: 0.5rem;
}
.new-method .formkit-options .formkit-option .formkit-inner {
    display: none;
}
.new-method .formkit-options .formkit-option {
    flex: 1 1 0%;
}
.new-method .formkit-options .formkit-option .formkit-label {
    display: flex;

    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    border: 1px solid #e2e8f0;
    background-color: #fff;
    color: #4a5568;
    font-size: 0.875rem;
    font-weight: 500;
    line-height: 1.25rem;
    transition: all 0.2s ease-in-out;
}
/* check if formkit-wrapper has the data property data-checked=true */
.new-method
    .formkit-options
    .formkit-option
    .formkit-wrapper[data-checked="true"]
    .formkit-label {
    background-color: #29419b !important;
    border-color: #ebf0fe !important;
    color: white !important;
}
</style>
