<script lang='ts' setup>
import type { GenericObject } from "vee-validate";
import type { RwaIssuanceProductBody } from "@/api/types";
import { useRouteQuery } from "@vueuse/router";
import { useI18n } from "vue-i18n";
import { client, safeClient } from "@/api";
import Base from "./base.vue";
import Done from "./done.vue";
import IssuePeriod from "./issue-period.vue";

const { t } = useI18n();
const { data: categories, onFetchResponse } = await safeClient(() => client.api.rwa.category.categories.get());

const step = useRouteQuery<number>("step", 1, { transform: v => Number(v), mode: "push" });
const initialData: RwaIssuanceProductBody = {
  product: {
    name: "",
    code: "",
    categoryId: categories.value?.data && categories.value?.data!.length > 0 ? categories.value?.data![0].id : "",
  },
  editions: [
    {
      editionName: "",
      launchDate: new Date(),
      perUserLimit: "",
      subscriptionStartDate: new Date(),
      subscriptionEndDate: new Date(),
      totalSupply: "",
      unitPrice: "",
      dividendRate: "",
    },
  ],
};
const form = useStorage<RwaIssuanceProductBody>("issuing-apply-form", { ...initialData });

onFetchResponse(() => {
  if (!form.value.product.categoryId && categories.value?.data && categories.value?.data.length > 0) {
    form.value.product.categoryId = categories.value?.data![0].id;
  }
});

function handleNext(values: GenericObject) {
  form.value.product = { ...values as any };
  step.value = 2;
}

async function handleSubmit(editions: RwaIssuanceProductBody["editions"]) {
  form.value.editions = editions;
  await client.api.rwa.issuance.products.bundle_and_submit.post(form.value);
  form.value = { ...initialData };
  step.value = 3;
}
</script>

<template>
  <IonPage>
    <ion-header>
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>{{ t('asset.issue.apply.title') }}</ion-title>
      </ion-toolbar>
    </ion-header>
    <IonContent :fullscreen="true" class="ion-padding">
      <Base v-if="step === 1" :initial-data="form.product" :categories="categories" @next="handleNext" />
      <IssuePeriod v-else-if="step === 2" :initial-data="form.editions" @submit="handleSubmit" />
      <Done v-else />
    </IonContent>
  </IonPage>
</template>
