const useStripeStore = Pinia.defineStore({
  id: "stripe",
  state: () => ({
    stripeData: {
      loading: false,
      paymentMethodCreated: false,
      complete: false,
      card: {
        id: `stripe-card-${Math.round(Math.random() * 99999)}`,
        instance: false,
      },
      billing_details: {
        name: null,
        unit: null,
        line1: null,
        country_code: null,
        postal_code: null,
        state_code: null,
        address: {
          line1: null,
          state: null,
          city: null,
          country: null,
          postal_code: null,
        },
      },
      stripe: false,
    },
    valueRadio: null,
    form: null,
    cardValidation: { show: false, message: null, type: "" },
    errorStripeMessage: "",
    clearAddress: false,
    paymentMethod: {},
  }),
  actions: {
    init() {
      const { stripe } = this.stripeData;
      const elements = stripe.elements();
      let card = elements.create("card", { disableLink: true });

      card.mount(`#${this.stripeData.card.id}`);
      this.stripeData.card.instance = card;

      card.on("change", async (event) => {
        this.stripeData.complete = event.complete;
        if (event.error) {
          this.errorStripeMessage = event.error.message;
        } else {
          this.errorStripeMessage = "";
        }
      });
    },
    async createPaymentMethod(notClear = false) {
      this.cardValidation.show = false;
      this.cardValidation.message = "";
      this.cardValidation.type = "";

      const { valid } = await this.form.validate();
      if (!valid || !this.stripeData.complete) return;

      this.stripeData.loading = true;
      const result = await this.stripeData.stripe.createPaymentMethod({
        type: "card",
        card: this.stripeData.card.instance,
        billing_details: {
          name: this.stripeData.billing_details.name,
          email: useUserStore().getUser.login,
          address: {
            line1: `${this.stripeData.billing_details.unit} ${this.stripeData.billing_details.line1}`,
            state: this.stripeData.billing_details.state_code?.toUpperCase(),
            country: this.stripeData.billing_details.country_code?.toUpperCase(),
            postal_code: this.stripeData.billing_details.postal_code,
            city: this.stripeData.billing_details.city,
          },
        },
      });

      if (result?.error) {
        this.cardValidation.show = true;
        this.cardValidation.message = result.error.message;
        this.cardValidation.type = "error";
        this.stripeData.loading = false;
        return;
      }

      const value = {
        stripe_customer_id: null,
        stripe_payment_method_id: result.paymentMethod.id,
        country: result.paymentMethod.card.country,
        name: [
          result.paymentMethod.name,
          result.paymentMethod.card.brand,
          result.paymentMethod.card.last4,
        ]
          .filter((v) => v)
          .join(" "),
        brand: result.paymentMethod.card.brand,
        exp_month: result.paymentMethod.card.exp_month,
        exp_year: result.paymentMethod.card.exp_year,
        funding: result.paymentMethod.card.funding,
        last4: result.paymentMethod.card.last4,
        main: 0,
        card_types: [],
      };

      await this.addPayment(result.paymentMethod, value, notClear);
    },
    async addPayment(payment, v, notClear) {
      const financial = {
        financial: {
          customer: {
            name: payment.billing_details.name,
            email: payment.billing_details.email,
            address: payment.billing_details.address.line1,
            city: payment.billing_details.address.city,
            state: payment.billing_details.address.state,
            country: payment.billing_details.address.country,
            postcode: payment.billing_details.address.postal_code,
            customer_type: "guest",
            origin: "guest",
            main: 1,
          },
          stripe: payment,
          card_type: {
            type: "booking",
            main: 1,
          },
        },
      };

      await axios
        .post(`/vendor/financial/stripe/store_customer`, financial, {
          headers: { SearchAndStayApiToken: "null" },
        })
        .then((r) => {
          this.paymentMethod = r.data.data.payment_methods.find(
            (m) => m.stripe_payment_method_id === v.stripe_payment_method_id
          );
          // emit("update:modelValue", paymentMethod);

          this.cardValidation.show = true;
          this.cardValidation.message = r.data.message;
          this.cardValidation.type = "success";
          this.stripeData.paymentMethodCreated = true;

          if (!notClear) {
            this.stripeData.billing_details = {
              name: null,
              unit: null,
              line1: null,
              country_code: null,
              postal_code: null,
              state_code: null,
              address: {
                line1: null,
                state: null,
                city: null,
                country: null,
                postal_code: null,
              },
          };
          this.clearAddress = true;
          this.stripeData.card.instance.clear();
          }

          setTimeout(() => {
            this.stripeData.paymentMethodCreated = false;
          }, 2000);
        })
        .catch((e) => {
          this.cardValidation.show = true;
          this.cardValidation.message = e.response.data.message;
          this.cardValidation.type = "error";

          this.stripeData.card.instance.clear();
        })
        .finally(() => {
          this.stripeData.loading = false;
          this.clearAddress = false;
        });
    },
  },
  getters: {},
});

window.useStripeStore = useStripeStore;
