<script lang='ts' setup>
import type { GenericObject } from "vee-validate";
import type { BankAccountsData, WithdrawBody } from "@/api/types";
import type { FormInstance } from "@/utils";
import { loadingController, modalController, toastController } from "@ionic/vue";
import { ErrorMessage, Field, Form } from "vee-validate";
import { client, safeClient } from "@/api";
import { AssetCodeEnum, ChainEnum, WithdrawMethodEnum } from "@/api/enum";
import { getCryptoIcon } from "@/config/crypto";
import SelectBankAccount from "./components/select-bank-account.vue";
import SelectCurrency from "./components/select-currency.vue";
import { createWithdrawSchema } from "./rules";

const { t } = useI18n();
const router = useRouter();
const walletStore = useWalletStore();
await walletStore.syncFundingBalances();
const { fundingBalances } = storeToRefs(walletStore);
const formInst = useTemplateRef<FormInstance>("formInst");

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 === (formInst.value?.getValues().assetCode || initialValues.assetCode));
  return Number(balance ? balance.available : "0").toFixed(2);
});

const schema = computed(() => createWithdrawSchema(t, maxAmount.value));
const currentBankAccount = ref<BankAccountsData | null>(null);

async function openSelectCurrency() {
  const modal = await modalController.create({
    component: SelectCurrency,
    componentProps: {
      onSelect: (code: string) => {
        formInst.value?.setFieldValue("assetCode", code);
      },
    },
    breakpoints: [0, 0.8],
    initialBreakpoint: 0.8,
    handle: true,
  });
  await modal.present();
}
async function openSelectBankAccount() {
  const modal = await modalController.create({
    component: SelectBankAccount,
    componentProps: {
      onSelect: (item: BankAccountsData) => {
        currentBankAccount.value = item;
        formInst.value?.setFieldValue("bankAccountId", item.id);
      },
    },
    breakpoints: [0, 0.8],
    initialBreakpoint: 0.8,
    handle: true,
  });
  await modal.present();
}

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
        ref="formInst"
        :validation-schema="schema"
        :initial-values="initialValues"
        @submit="onSubmit"
      >
        <div class="flex flex-col gap-5">
          <div>
            <Field name="assetCode">
              <template #default="{ value }">
                <ion-label class="block text-sm font-medium mb-2">
                  选择币种
                </ion-label>
                <div
                  class="flex items-center justify-between bg-faint rounded-2xl p-4 cursor-pointer"
                  @click="openSelectCurrency"
                >
                  <div class="flex items-center gap-3">
                    <component :is="getCryptoIcon(value)" class="w-8 h-8" />
                    <span class="text-base font-medium">{{ value }}</span>
                  </div>
                  <ion-icon name="chevron-forward-outline" class="text-text-400" />
                </div>
              </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">
                  <template #default>
                    <ion-label class="block text-sm font-medium mb-2">
                      {{ t('withdraw.bankAccountId') }}
                    </ion-label>
                    <div
                      class="flex items-center justify-between bg-faint rounded-2xl p-4 cursor-pointer"
                      @click="openSelectBankAccount"
                    >
                      <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-md mr-2 flex items-center justify-center text-white font-bold text-xs shadow-sm bg-[#0F5AA6]">
                          <span class="text-white">{{ currentBankAccount?.bankCode }}</span>
                        </div>
                        <span class="text-base font-medium">{{ currentBankAccount?.bankName }}</span>
                      </div>
                      <ion-icon name="chevron-forward-outline" class="text-text-400" />
                    </div>
                  </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>
