<script lang='ts' setup>
import type { GenericObject } from "vee-validate";
import type { WithdrawBody } from "@/api/types";
import { loadingController, toastController } from "@ionic/vue";
import { ErrorMessage, Field, Form } from "vee-validate";
import { client, safeClient } from "@/api";
import { AssetCodeEnum, ChainEnum, WithdrawMethodEnum } from "@/api/enum";
import { createWithdrawSchema } from "./rules";

const { t } = useI18n();
const router = useRouter();
const walletStore = useWalletStore();
const { fundingBalances, bankAccounts } = storeToRefs(walletStore);

const initialValues: WithdrawBody = {
  assetCode: AssetCodeEnum.USDT,
  amount: "",
  withdrawMethod: WithdrawMethodEnum.BANK,
  toAddress: "",
  bankAccountId: "",
  chain: "BEP20",
};

const maxAmount = computed(() => {
  const balance = fundingBalances.value?.find(item => item.assetCode === initialValues.assetCode);
  return balance ? balance.available : "0";
});

const schema = computed(() => createWithdrawSchema(t, maxAmount.value));

async function onSubmit(values: GenericObject) {
  const loading = await loadingController.create({
    message: "提交中...",
  });
  await loading.present();

  await safeClient(() => client.api.withdraw.post(values as WithdrawBody)).finally(async () => {
    const toast = await toastController.create({
      message: t("withdraw.successMessage"),
      duration: 2000,
      position: "bottom",
      color: "success",
    });

    await toast.present();
    loading.dismiss();
    router.back();
  });
}
</script>

<template>
  <ion-page>
    <IonHeader>
      <ion-toolbar class="ion-toolbar">
        <ion-buttons slot="start">
          <ui-back-button />
        </ion-buttons>
        <ion-title>{{ t("withdraw.title") }}</ion-title>
      </ion-toolbar>
    </IonHeader>
    <IonContent :fullscreen="true" class="ion-padding">
      <Form
        :validation-schema="schema"
        :initial-values="initialValues"
        @submit="onSubmit"
      >
        <div class="flex flex-col gap-5">
          <div>
            <Field name="assetCode">
              <template #default="{ field, value }">
                <ion-radio-group v-bind="field" :model-value="value">
                  <ion-label class="text-sm">
                    {{ t("withdraw.chooseCurrency") }}
                  </ion-label>
                  <ion-item v-for="item in AssetCodeEnum" :key="item">
                    <ion-radio :value="item" justify="space-between">
                      {{ t(`withdraw.assetCode.${item}`) }}
                    </ion-radio>
                  </ion-item>
                </ion-radio-group>
              </template>
            </Field>
            <ErrorMessage name="assetCode" class="text-red-500 text-xs mt-1" />
          </div>

          <div>
            <Field name="withdrawMethod">
              <template #default="{ field, value }">
                <ion-radio-group v-bind="field" :model-value="value">
                  <ion-label class="text-sm">
                    {{ t("withdraw.chooseMethod") }}
                  </ion-label>
                  <ion-item v-for="item in WithdrawMethodEnum" :key="item">
                    <ion-radio :value="item" justify="space-between">
                      {{ t(`withdraw.method.${item}`) }}
                    </ion-radio>
                  </ion-item>
                </ion-radio-group>
              </template>
            </Field>
            <ErrorMessage name="withdrawMethod" class="text-red-500 text-xs mt-1" />
          </div>

          <Field name="withdrawMethod">
            <template #default="{ value: withdrawMethod }">
              <div v-if="withdrawMethod === WithdrawMethodEnum.BANK">
                <Field name="bankAccountId" type="text">
                  <template #default="{ field }">
                    <ion-select
                      v-bind="field"
                      class="ui-select"
                      interface="action-sheet"
                      toggle-icon=""
                      :label="t('withdraw.bankAccountId')"
                      :placeholder="t('withdraw.enterBankAccountId')"
                    >
                      <ion-select-option v-for="item in bankAccounts" :key="item.id" :value="item.id">
                        {{ item.bankName }} - {{ item.maskAccountNumber }}
                      </ion-select-option>
                    </ion-select>
                  </template>
                </Field>
                <ErrorMessage name="bankAccountId" class="text-red-500 text-xs mt-1" />
              </div>

              <template v-else-if="withdrawMethod === WithdrawMethodEnum.CRYPTO">
                <div>
                  <Field name="chain">
                    <template #default="{ field, value }">
                      <ion-radio-group v-bind="field" :model-value="value">
                        <ion-label class="text-sm">
                          {{ t("withdraw.chooseChain") }}
                        </ion-label>
                        <ion-item v-for="item in ChainEnum" :key="item">
                          <ion-radio :value="item" justify="space-between">
                            {{ item }}
                          </ion-radio>
                        </ion-item>
                      </ion-radio-group>
                    </template>
                  </Field>
                  <ErrorMessage name="chain" class="text-red-500 text-xs mt-1" />
                </div>

                <div>
                  <Field name="toAddress">
                    <template #default="{ field }">
                      <ui-input-label
                        v-bind="field"
                        :label="t('withdraw.cryptoAddress')"
                        :placeholder="t('withdraw.enterCryptoAddress')"
                        type="text"
                        inputmode="text"
                      />
                    </template>
                  </Field>
                  <ErrorMessage name="toAddress" class="text-red-500 text-xs mt-1" />
                </div>
              </template>
            </template>
          </Field>

          <div>
            <Field name="amount">
              <template #default="{ field }">
                <ui-input-label
                  v-bind="field"
                  :label="t('withdraw.amount')"
                  :placeholder="t('withdraw.enterAmountMax', { amount: maxAmount })"
                  type="number"
                  inputmode="numeric"
                />
              </template>
            </Field>
            <ErrorMessage name="amount" class="text-red-500 text-xs mt-1" />
          </div>

          <ion-button expand="block" type="submit" shape="round" color="success">
            {{ t("withdraw.submit") }}
          </ion-button>
        </div>
      </Form>
    </IonContent>
  </ion-page>
</template>

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