<template>
  <a-modal
    v-model="visible"
    :title="trans('Create request')"
    :after-close="() => $emit('close')"
    :destroy-on-close="true"
    :width="960"
  >
    <a-form
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      label-align="left"
      @keypress.enter.native="submit"
    >
      <div class="flex space-x-3">
        <div class="w-8/12">
          <a-form-item
            :label="trans('Your name')"
          >
            <a-input v-model="form.name" :placeholder="trans('Your name')" />
            <template v-if="validationErrorsObj.name">
              <span class="validation-error" v-for="item in validationErrorsObj.name" :key="item">{{ item }}</span>
            </template>
          </a-form-item>
          <a-form-item
            :label="trans('Phone')"
          >
            <vue-country-code
              @onSelect="onSelect"
              :preferredCountries="['tm']"
              :defaultCountry="'tm'">
            </vue-country-code>
            <span>{{ countryCode }}</span>
            <a-input v-model="form.phone" :placeholder="trans('Phone')" />
            <template v-if="validationErrorsObj.phone">
              <span class="validation-error" v-for="item in validationErrorsObj.phone" :key="item">{{ item }}</span>
            </template>
          </a-form-item>
          <a-form-item
            :label="trans('Email')"
          >
            <a-input v-model="form.email" :placeholder="trans('Email')" />
            <template v-if="validationErrorsObj.email">
              <span class="validation-error" v-for="item in validationErrorsObj.email" :key="item">{{ item }}</span>
            </template>
          </a-form-item>
          <a-form-item
            :label="'Password'"
          >
            <a-input v-model="form.password" type="password" :placeholder="trans('Password')" />
            <template v-if="validationErrorsObj.password">
              <span class="validation-error" v-for="item in validationErrorsObj.password" :key="item">{{ item }}</span>
            </template>
          </a-form-item>
          <a-form-item :label="trans('Type')">
            <a-radio-group v-model="type" button-style="solid">
              <a-radio-button value="local">
                {{ trans("Local") }}
              </a-radio-button>
              <a-radio-button value="int">
                {{ trans("Inter") }}
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
        </div>
        <div class="w-2/12"></div>
      </div>
      <div
        class="flex relative space-x-3"
        v-for="(item, index) in form.items"
        :key="item.id"
      >
        <div class="absolute bottom-8 -left-3 w-5 text-right">
          {{ index + 1 }}.
        </div>
        <a-form-item
          class="w-full"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
          label-align="left"
        >
          <a-input :value="item.title" disabled />
        </a-form-item>
        <!-- <a-form-item
          class="w-3/12"
          :label="index === 0 ? 'Mukdary' : ''"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
          label-align="left"
          :validateStatus="formStatus(`items.${index}.count`)"
        >
          <a-input v-model.number="item.count" :addon-after="item.unit" />
        </a-form-item> -->
      </div>
    </a-form>
    <div class="border-t pt-4 border-gray-300 text-right">
      <span class="font-bold"
        >{{ trans("Total") }}: {{ selectedItems.length }} x {{ price }}
        {{ currency }} =</span
      >
      <span class="font-bold text-primary"
        >{{ totalPrice }} {{ currency }}</span
      >
    </div>
    <div slot="footer" class="flex items-center justify-end">
      <!-- <google-re-captcha-v3
        ref="captcha"
        v-model="form.captcha"
        inline
        action="create_request"
      /> -->
      <a-button
        type="primary"
        class="ml-5"
        size="large"
        @click="submit"
        :loading="form.processing"
        :disabled="loader"
        >{{ loader ? '...' : trans("Create") }}</a-button
      >
    </div>
  </a-modal>
</template>

<script>
// import GoogleReCaptchaV3 from "./GoogleReCaptchaV3";
export default {
  props: {
    selectedItems: { type: Array, default: () => [] },
  },

  // components: {
  //   GoogleReCaptchaV3,
  // },

  data() {
    return {
      visible: true,
      type: "local",
      form: this.$inertia.form({
        name: undefined,
        phone: undefined,
        email: undefined,
        password: undefined,
        captcha: undefined,
        items: [
          {
            id: undefined,
            title: undefined,
            // count: undefined,
          },
        ],
      }),
      validationErrorsObj: {},
      loader: false,
      countryCode: '',
    };
  },

  computed: {
    currency() {
      return this.type === "local" ? "TMT" : "USD";
    },

    price() {
      const { local_price, int_price } = this.$page.props;
      return this.type === "local" ? local_price : int_price;
    },

    totalPrice() {
      return this.selectedItems.length * this.price;
    },
  },

  mounted() {
    this.fill();
  },

  beforeDestroy() {
    window.location.reload();
  },

  methods: {
    fill() {
      this.form = {
        ...this.form,
        items: this.selectedItems.map((item) => ({
          ...item,
          // count: undefined,
        })),
      };
    },

    onSelect({name, iso2, dialCode}) {
      console.log(name, iso2, dialCode);
      this.countryCode = dialCode
    },

    submit() {
      // this.form.post(this.route('requests.store'), {
      //   onSuccess: (res) => {
      //     alert('we are in success section')
      //     console.log(res.hello)
      //     this.visible = false;
      //     this.$message.success(this.trans("Success message"));
          
      //   },
      //   onError: (error) => {
      //     alert('we are in errors section')
      //     if (error) {
      //       this.$message.error('Invalida data');
      //     }
      //   },
      // })
      this.loader = true

      fetch(this.route('requests.store'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify(this.form) // body data type must match "Content-Type" header
      })
      .then(res => res.json())
      .then(res => {
        alert('we are in success section')
        switch (res.status) {
          
          case 400: // validation failed
            this.validationErrorsObj = {}

            // this.errorsArr = []

            let errorValidation = res.validationErrors

            for (let key in errorValidation) {
              
              this.validationErrorsObj[key] = []

              for(let i = 0; i < errorValidation[key].length; i++) {
                this.validationErrorsObj[key].push(errorValidation[key][i])
              }
            }
            console.log(this.validationErrorsObj)
            break;
          
          case 401: // not registered yet or invalid credentials
            this.$message.error('Unauthorized');
            break;
          
          case 500:
            this.$message.error('Internal Server Error');
            break;

          case 201: // success: withdraw from a balance and create a request
            this.visible = false;
            this.$message.success(this.trans("Success message"));
            break;

          case 300: // not enough money on a balance
            this.$message.error(res.message);
            break;
          
          default:
            this.$message.error('Something went wrong. Try later.');
            break;
        }

        this.loader = false
      })
      .catch(err => {
        alert('we are in errors section')
        console.log(err)
        this.loader = false
      })
    },
  },
};
</script>

<style>
.validation-error {
  color: rgb(255, 0, 0);
}
</style>
