<template>
  <div class="step-3">
    <div class="ptc-block">
      <div class="ptc-inner">
        <p class="ptc-label">Version & Price</p>
        <div class="detail">
          <strong class="s1 ellipsis" :title="getters.selectedProduct.name">{{
            getters.selectedProduct.name
          }}</strong>
          <span class="fls0" style="font-size: 0"
            ><strong class="s2">${{ getters.cost }}</strong
            ><span class="s3">{{
              state.form.subscribe_type === 'year' ? 'Annual' : 'Monthly'
            }}</span></span
          >
          <strong class="s4 fls0" @click="$emit('go', -2)">Modify ></strong>
        </div>
      </div>
    </div>
    <div class="ptc-wrapper">
      <div class="ptc-block">
        <div class="ptc-inner">
          <p class="ptc-label">Phone model</p>
          <div class="detail">
            <strong class="s1">{{ getters.modelName }}</strong>
            <strong class="s4" @click="$emit('go', -1)">Modify ></strong>
          </div>
        </div>
      </div>
      <div v-if="rootState.userInfo" class="ptc-button-group">
        <div class="ptc-inner">
          <button class="ptc-button" :loading="loading" @click="submit">
            SUBMIT
          </button>
        </div>
      </div>
    </div>
    <div v-if="!rootState.userInfo" class="ptc-wrapper">
      <div class="ptc-block">
        <div class="ptc-inner">
          <p class="text">
            Please enter a valid email address, we will send you the latest
            status of the order through this contact method.
          </p>
          <input
            v-model="state.form.email"
            class="ptc-input"
            placeholder="email address"
          />
        </div>
      </div>
      <div class="ptc-button-group">
        <div class="ptc-inner">
          <button class="ptc-button" :loading="loading" @click="submit">
            SUBMIT
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { string } from 'yup'
import { state, getters } from './store'
import { state as rootState } from '@/store'
import { checkoutOrder } from '@/service/order'
import Toast from '@/components/toast'

defineEmits<{
  (e: 'go', delta?: number): void
}>()

const loading = ref(false)

async function submit() {
  loading.value = true
  try {
    let schema = string().email('Please enter a valid email address')
    if (!rootState.userInfo) schema = schema.required('Email is required')
    await schema.validate(state.form.email)
    const { results } = await checkoutOrder(state.form)
    location.href = results
  } catch (err) {
    Toast(err.message)
  }
  loading.value = false
}
</script>

<style lang="scss" scoped>
.ptc-wrapper + .ptc-wrapper {
  margin-top: 24px;
}
.text {
  margin-bottom: 48px;
  line-height: 44px;
  font-size: 32px;
  color: #333;
}
</style>
