<script lang='ts' setup>
import type { GenericObject } from "vee-validate";
import type { RwaIssuanceProductBody } from "@/api/types";
import { toTypedSchema } from "@vee-validate/yup";
import { addOutline, removeOutline } from "ionicons/icons";
import { ErrorMessage, Field, FieldArray, Form } from "vee-validate";
import { useI18n } from "vue-i18n";
import * as yup from "yup";

const props = defineProps<{
  initialData: RwaIssuanceProductBody["editions"];
}>();
const emit = defineEmits<{
  (e: "submit", values: RwaIssuanceProductBody["editions"]): void;
}>();
const { t } = useI18n();
const now = useNow();

const initialIssuePeriod: RwaIssuanceProductBody["editions"][0] = {
  editionName: "",
  launchDate: new Date(),
  perUserLimit: "",
  subscriptionStartDate: new Date(),
  subscriptionEndDate: new Date(),
  totalSupply: "",
  unitPrice: "",
  dividendRate: "",
};

const initialValues = ref({
  editions: props.initialData || [{ ...initialIssuePeriod }],
});

const launchDate = ref(new Date().toISOString());
const subscriptionStartDate = ref(new Date().toISOString());
const subscriptionEndDate = ref(new Date().toISOString());

const schema = toTypedSchema(yup.object({
  editions: yup.array().of(
    yup.object({
      editionName: yup.string().required(t("asset.issue.apply.validation.editionNameRequired")),
      launchDate: yup.string()
        .required(t("asset.issue.apply.validation.launchDateRequired"))
        .test("not-past", t("asset.issue.apply.validation.launchDateNotPast"), (value) => {
          if (!value)
            return true;
          return new Date(value) >= new Date(now.value.toDateString());
        })
        .test("before-subscription", t("asset.issue.apply.validation.launchBeforeSubscription"), (value) => {
          if (!value || !subscriptionStartDate.value)
            return true;
          return new Date(value) < new Date(subscriptionStartDate.value);
        }),
      subscriptionStartDate: yup.string()
        .required(t("asset.issue.apply.validation.subscriptionStartDateRequired"))
        .test("not-past", t("asset.issue.apply.validation.subscriptionStartDateNotPast"), (value) => {
          if (!value)
            return true;
          return new Date(value) >= new Date(now.value.toDateString());
        })
        .test("after-launch", t("asset.issue.apply.validation.subscriptionAfterLaunch"), (value) => {
          if (!value || !launchDate.value)
            return true;
          return new Date(value) > new Date(launchDate.value);
        }),
      subscriptionEndDate: yup.string()
        .required(t("asset.issue.apply.validation.subscriptionEndDateRequired"))
        .test("after-start", t("asset.issue.apply.validation.subscriptionEndAfterStart"), (value) => {
          if (!value || !subscriptionStartDate.value)
            return true;
          return new Date(value) > new Date(subscriptionStartDate.value);
        }),
      perUserLimit: yup.string().required(t("asset.issue.apply.validation.perUserLimitRequired")),
      totalSupply: yup.string().required(t("asset.issue.apply.validation.totalSupplyRequired")),
      unitPrice: yup.string().required(t("asset.issue.apply.validation.unitPriceRequired")),
      dividendRate: yup.string().required(t("asset.issue.apply.validation.dividendRateRequired")),
    }),
  ),
}));

function handleSubmit(values: GenericObject) {
  emit("submit", values.editions);
}
</script>

<template>
  <Form :validation-schema="schema" :initial-values="initialValues" class="space-y-5" @submit="handleSubmit">
    <FieldArray v-slot="{ fields, push, remove }" name="editions">
      <ui-collapse v-for="(entry, idx) in fields" :key="entry.key" :title="t('asset.issue.apply.issuePeriodIndex', { index: idx + 1 })" size="small">
        <div>
          <Field :name="`editions[${idx}].editionName`">
            <template #default="{ field, errorMessage }">
              <ui-input-label
                v-bind="field"
                :label="t('asset.issue.apply.editionName')"
                :placeholder="t('asset.issue.apply.enterEditionName')"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].perUserLimit`" type="text">
            <template #default="{ field, errorMessage }">
              <ui-input-label
                v-bind="field"
                type="number"
                inputmode="numeric"
                :label="t('asset.issue.apply.perUserLimit')"
                :placeholder="t('asset.issue.apply.enterPerUserLimit')"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].totalSupply`" type="text">
            <template #default="{ field, errorMessage }">
              <ui-input-label
                v-bind="field"
                type="number"
                inputmode="numeric"
                :label="t('asset.issue.apply.totalSupply')"
                :placeholder="t('asset.issue.apply.enterTotalSupply')"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
          <ErrorMessage :name="`editions[${idx}].totalSupply`" />
        </div>

        <div>
          <Field :name="`editions[${idx}].unitPrice`" type="text">
            <template #default="{ field, errorMessage }">
              <ui-input-label
                v-bind="field"
                type="number"
                inputmode="numeric"
                :label="t('asset.issue.apply.unitPrice')"
                :placeholder="t('asset.issue.apply.enterUnitPrice')"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].dividendRate`" type="number">
            <template #default="{ field, errorMessage }">
              <ui-input-label
                v-bind="field"
                type="number"
                inputmode="numeric"
                :label="t('asset.issue.apply.dividendRate')"
                :placeholder="t('asset.issue.apply.enterDividendRate')"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].launchDate`">
            <template #default="{ field, errorMessage }">
              <ui-datetime
                v-bind="field"
                v-model="launchDate"
                datetime="launchDate"
                :label="t('asset.issue.apply.launchDate')"
                :min="now.toISOString()"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].subscriptionStartDate`">
            <template #default="{ field, errorMessage }">
              <ui-datetime
                v-bind="field"
                v-model="subscriptionStartDate"
                datetime="subscriptionStartDate"
                :label="t('asset.issue.apply.subscriptionStartDate')"
                :min="launchDate ? new Date(launchDate).toISOString() : now.toISOString()"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <div>
          <Field :name="`editions[${idx}].subscriptionEndDate`">
            <template #default="{ field, errorMessage }">
              <ui-datetime
                v-bind="field"
                v-model="subscriptionEndDate"
                datetime="subscriptionEndDate"
                :label="t('asset.issue.apply.subscriptionEndDate')"
                :min="subscriptionStartDate ? new Date(subscriptionStartDate).toISOString() : now.toISOString()"
              />
              <div v-if="errorMessage" class="text-xs text-red-500 mt-1">
                {{ errorMessage }}
              </div>
            </template>
          </Field>
        </div>

        <ion-button color="tertiary" size="small" class="ui-button" @click="remove(idx)">
          <ion-icon slot="start" :icon="removeOutline" />
          <span>{{ t('asset.issue.apply.removeItem') }}</span>
        </ion-button>
      </ui-collapse>

      <ion-button expand="block" fill="outline" @click="push({ ...initialIssuePeriod })">
        <ion-icon slot="icon-only" :icon="addOutline" />
        <span>{{ t('asset.issue.apply.addStep') }}</span>
      </ion-button>
    </FieldArray>

    <div class="flex justify-center space-x-4">
      <ion-button expand="block" shape="round" fill="outline" class="w-40" @click="$router.back()">
        {{ t('asset.issue.apply.back') }}
      </ion-button>
      <ion-button expand="block" type="submit" class="w-full" shape="round" color="success">
        {{ t('asset.issue.apply.submit') }}
      </ion-button>
    </div>
  </Form>
</template>

<style lang='css' scoped></style>
