<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 now = useNow();
const { data: categories } = await safeClient(() => client.api.rwa.issuance.categories.get());

const step = useRouteQuery<number>("step", 1, { transform: v => Number(v), mode: "push" });
const initialData: RwaIssuanceProductBody = {
  product: {
    name: "",
    code: "",
    categoryId: categories.value!.length > 0 ? categories.value![0].id : "",
  },
  editions: [
    {
      editionName: "",
      launchDate: useDateFormat(now.value, "YYYY/MM/DD").value,
      perUserLimit: "",
      subscriptionDeadline: useDateFormat(now.value, "YYYY/MM/DD").value,
      totalSupply: "",
      unitPrice: "",
      dividendRate: "",
    },
  ],
};
const form = useStorage<RwaIssuanceProductBody>("issuing-apply-form", { ...initialData });

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.post(form.value);
  form.value = { ...initialData };
  step.value = 3;
}
</script>

<template>
  <IonPage>
    <ion-header>
      <ion-toolbar class="ui-toolbar">
        <ion-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>
