<template>
  <div class="create-invoice">
    <Transition
      name="fade"
      mode="out-in"
    >
      <PageForm
        v-if="!invoiceLink"
        title="Creating invoice"
        :back-link="`/projects/${$route.params.projectId}/invoices`"
        :back-text="$t('back_to', [project.name])"
        :submit-text="$t('create')"
        :handler="onSubmit"
      >
        <UiInput
          id="amount"
          label="Invoice amount"
          rules="required"
          :mask="{ mask: Number }"
        >
          <template #suffix>
            <CurrencyName
              code="USDT"
              size="small"
            />
          </template>
        </UiInput>
      </PageForm>

      <div
        v-else
        class="create-invoice__summary"
      >
        <UiButton
          icon="chevron-left"
          color="secondary"
          type="link"
          class="mb-8"
          :href="`/projects/${$route.params.projectId}/invoices`"
        >
          {{ $t('back_to', [project.name]) }}
        </UiButton>

        <h1 class="mb-32">
          Invoice created
        </h1>

        <UiAlert
          type="neutral"
          class="mb-24"
        >
          <span> Creation time</span>
          {{ dayjs().format('DD.MM.YY HH:mm') }}.
          <span>It will expires in </span>
          <strong>30 minutes.</strong>
        </UiAlert>

        <UiInput
          id="invoice_link"
          copyable
          inputmode="none"
          label="Ссылка на счет"
          :model-value="invoiceLink"
          readonly
        />

        <UiButton
          size="large"
          class="w-100 mt-24"
          :href="`/projects/${route.params.projectId}/invoices`"
        >
          Done
        </UiButton>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { v4 as uuidv4 } from 'uuid'
import dayjs from 'dayjs'

definePageMeta({
  middleware: ['auth'],
  centerContent: true,
})

const route = useRoute()

const { data: project } = await useAsyncData(
  'project',
  () =>
    $api(`/online_stores/${route.params.projectId}`, {
      method: 'get',
    }),
  {},
)

if (!project.value) {
  throw createError({
    statusCode: 404,
    statusMessage: 'Page Not Found',
  })
}

const notify = useNotify()
const runtimeConfig = useRuntimeConfig()

const invoiceLink = ref('')

async function onSubmit(values) {
  try {
    const result = await $api('/invoices', {
      method: 'post',
      body: {
        ...values,
        currencyCode: 'USDT',
        onlineStoreId: +route.params.projectId,
        orderId: uuidv4(),
      },
    })

    invoiceLink.value = `${runtimeConfig.public.payHost}/${result.invoiceId}`

    notify({
      type: 'positive',
      text: 'Инвойс успешно создан',
    })
  }
  catch (e) {
    setStaticError({
      status: e.status,
      message: 'Something went wrong',
    })
  }
}
</script>

<style lang="scss">
.create-invoice {
  &__summary {
    width: 500px;
    margin: 0 auto;
  }
}
</style>
