<template>
  <form id="cardForm">
    <v-col cols="12">
      <v-row>
        <v-col cols="2" md="1">
          <v-card tile flat :disabled="amexCard" class="cardpayment-card-disabled">
            <v-img src="@/assets/pmtImage1.png"></v-img>
          </v-card>
        </v-col>
        <v-col cols="2" md="1">
          <v-card tile flat :disabled="visaCard" class="cardpayment-card-disabled">
            <v-img src="@/assets/pmtImage2.png"></v-img>
          </v-card>
        </v-col>
        <v-col cols="2" md="1">
          <v-card tile flat :disabled="masterCard" class="cardpayment-card-disabled">
            <v-img src="@/assets/pmtImage3.png"></v-img>
          </v-card>
        </v-col>
        <v-col cols="2" md="1">
          <v-card tile flat :disabled="discoverCard" class="cardpayment-card-disabled">
            <v-img src="@/assets/pmtImage4.png"></v-img>
          </v-card>
        </v-col>
      </v-row>
    </v-col>
    <v-col cols="12" sm="6" md="6">
      <v-row>
        <v-col cols="12">
          <label for="cc-number">Credit card number</label>
          <div class="v-input cartpayment-input-field" id="cc-number"></div>
          <div class="required-feedback">Credit card number is required</div>
          <div class="invalid-feedback">Credit card number is invalid</div>
        </v-col>
        <v-col cols="5" class="py-0">
          <label for="cc-month">Expiration Month</label>
          <div class="v-input cartpayment-input-field" id="cc-month"></div>
          <div class="required-feedback">Expiration month is required</div>
          <div class="invalid-feedback">Expiration month is invalid</div>
        </v-col>
        <v-col cols="1" class="mt-2 mt-sm-0 mt-md-0 mt-lg-0">/</v-col>
        <v-col cols="5" class="py-0">
          <label for="cc-year">Expiration Year</label>
          <div class="v-input cartpayment-input-field mt-sm-0 mt-lg-0 mt-md-0" id="cc-year"></div>
          <div class="required-feedback">Expiration year is required</div>
          <div class="invalid-feedback">Expiration year is invalid</div>
        </v-col>
        <v-row class="pl-3 d-flex align-center">
          <v-col cols="7" class="pb-0">
            <label>Card Verification Number</label>
            <div class="v-input cartpayment-input-field" id="cc-cvn"></div>
            <div class="required-feedback">Security code is required</div>
            <div class="invalid-feedback">Security code is invalid</div>
          </v-col>
          <v-col cols="2" class="d-flex align-end pb-0">
            <v-tooltip v-model="showCVNHelp" right>
              <template v-slot:activator="{ on }">
                <v-btn icon v-on="on">
                  <v-icon color="grey lighten-1" @click="showCVNHelp = !showCVNHelp">mdi-help</v-icon>
                </v-btn>
              </template>
              <v-img src="@/assets/cvv.png"></v-img>
            </v-tooltip>
          </v-col>
        </v-row>
      </v-row>
    </v-col>
    <v-col cols="12">
      <v-btn
        depressed
        tile
        class="float-right text-uppercase"
        color="primary"
        @click="submitPayment()"
      >Place Order</v-btn>
    </v-col>
  </form>
</template>
<script>
/* eslint-disable */

const client = require("braintree-web/client");
const hostedFields = require("braintree-web/hosted-fields");

const braintreeAuthKey = process.env.VUE_APP_BRAINTREE_AUTH_KEY;
export default {
  name: "CardPayment",
  components: {},
  data: () => ({
    masterCard: true,
    visaCard: true,
    discoverCard: true,
    amexCard: true,
    paymentMethod: "",
    showCVNHelp: false,
    saveInAddressBook: false,
    showAddressDialog: false,
    userNewAddress: false,
    expiryMonth: "",
    creditCardNumber: "",
    creditCardCVN: "",
    expiryYear: "",
    hostedFieldsInstance: null,
    snackbar: {
      show: false,
      message: null,
      color: null,
      timeout: 0,
    },
  }),
  computed: {},
  methods: {
    placeOrder() {},
    submitPayment() {
      var formIsInvalid = false;
      var state = this.hostedFieldsInstance.getState();

      Object.keys(state.fields).forEach((field) => {
        state.fields[field].container.classList.remove("is-invalid");
        state.fields[field].container.classList.remove("is-required");

        if (state.fields[field].isEmpty) {
          state.fields[field].container.classList.add("is-required");
          formIsInvalid = true;
        } else if (!state.fields[field].isValid) {
          state.fields[field].container.classList.add("is-invalid");
          formIsInvalid = true;
        }
      });

      if (formIsInvalid) {
        // skip tokenization request if any fields are invalid
        return;
      }

      this.hostedFieldsInstance.tokenize({}, (err, payload) => {
        if (err) {
          console.error(err);
          return;
        }
        this.$emit("submitCardPayment", payload);
      });
    },
  },
  mounted() {
    let vm = this;
    if (!this.hostedFieldsInstance) {
      client.create(
        {
          authorization: braintreeAuthKey,
        },
        (err, clientInstance) => {
          if (err) {
            console.error(err);
            return;
          }

          hostedFields.create(
            {
              client: clientInstance,
              styles: {
                input: {
                  // change input styles to match
                  // bootstrap styles
                  "font-size": "1rem",
                  color: "#495057",
                  padding: "10px",
                },
              },
              fields: {
                number: {
                  selector: "#cc-number",
                  placeholder: "1111 1111 1111 1111",
                },
                expirationMonth: {
                  selector: "#cc-month",
                  placeholder: "MM",
                },
                expirationYear: {
                  selector: "#cc-year",
                  placeholder: "YY",
                },
                cvv: {
                  selector: "#cc-cvn",
                  placeholder: "111",
                },
              },
            },
            (err, hostedFieldsInstance) => {
              if (err) {
                console.error(err);
                return;
              }

              vm.hostedFieldsInstance = hostedFieldsInstance;

              hostedFieldsInstance.on("empty", (event) => {
                let field = event.fields[event.emittedBy];
                field.container.classList.remove("is-invalid");
                field.container.classList.add("is-required");
              });

              hostedFieldsInstance.on("notEmpty", (event) => {
                let field = event.fields[event.emittedBy];
                field.container.classList.remove("is-required");
              });

              hostedFieldsInstance.on("validityChange", (event) => {
                var field = event.fields[event.emittedBy];

                field.container.classList.remove("is-valid");
                field.container.classList.remove("is-invalid");
                field.container.classList.remove("is-required");

                if (field.isEmpty) {
                  field.container.classList.add("is-required");
                } else if (field.isValid) {
                  field.container.classList.add("is-valid");
                } else {
                  field.container.classList.add("is-invalid");
                }
              });

              hostedFieldsInstance.on("cardTypeChange", (event) => {
                if (event.cards.length === 1) {
                  var card = event.cards[0].type;
                  if (card == "visa") {
                    this.visaCard = false;
                  } else if (card == "master-card") {
                    this.masterCard = false;
                  } else if (card == "discover") {
                    this.discoverCard = false;
                  } else if (card == "american-express") {
                    this.amexCard = false;
                  }
                } else {
                  this.visaCard = true;
                  this.masterCard = true;
                  this.discoverCard = true;
                  this.amexCard = true;
                }
              });
            }
          );
        }
      );
    }
  },
  created() {},
};
</script>

<style src="./CardPayment.scss" lang="scss" scoped/>

