<script setup lang="ts">
import { BankBook } from 'stores/branch/types';
import useOptionStore from 'stores/options';
import { selectFilterOptionRefMod } from 'stores/utils';
import { onMounted, ref, watch } from 'vue';
import { deleteItem } from 'stores/utils';
import { QSelect } from 'quasar';
import { AddButton, DeleteButton } from 'components/button';
import ToggleButton from '../button/ToggleButton.vue';

import ImageHover from '../ImageHover.vue';

const optionStore = useOptionStore();

const bankBookList = defineModel<BankBook[]>('bankBookList', { default: [] });

const bankQrUrl = ref<string[]>([]);
const listIndex = ref(0);

const reader = new FileReader();
const inputFile = (() => {
  const _element = document.createElement('input');
  _element.type = 'file';
  _element.accept = 'image/*';
  _element.addEventListener('change', change);
  return _element;
})();
reader.addEventListener('load', () => {
  if (typeof reader.result === 'string')
    bankQrUrl.value[listIndex.value] = reader.result;
});

defineProps<{
  title?: string;
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  view?: boolean;
}>();

defineEmits<{
  (e: 'viewQr', index: number): void;
  (e: 'editQr', index: number): void;
}>();

const bankBookOptions = ref<Record<string, unknown>[]>([]);
let bankBoookFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

const accountTypeOptions = ref<Record<string, unknown>[]>([]);
let accountTypeFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

function addBankBook() {
  bankBookList.value?.push({
    bankName: '',
    accountNumber: '',
    bankBranch: '',
    accountName: '',
    accountType: '',
    currentlyUse: true,
  });
}

function change(e: Event) {
  const _element = e.target as HTMLInputElement | null;
  const _file = _element?.files?.[0];
  if (_file) {
    bankBookList.value[listIndex.value].bankQr = _file;
    reader.readAsDataURL(_file);
  }
}

onMounted(() => {
  if (optionStore.globalOption) {
    bankBoookFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.bankBook),
      bankBookOptions,
      'label',
    );

    accountTypeFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.accountType),
      accountTypeOptions,
      'label',
    );
  }
});

watch(
  () => optionStore.globalOption,
  () => {
    bankBoookFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.bankBook),
      bankBookOptions,
      'label',
    );

    accountTypeFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.accountType),
      accountTypeOptions,
      'label',
    );
  },
);
</script>
<template>
  <div class="row col-12">
    <div class="col-12 q-pb-sm text-weight-bold text-body1 row items-center">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-sm"
        color="info"
        name="mdi-bank-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`${title}`) }}
      <AddButton
        v-if="!readonly"
        id="btn-add-bank"
        icon-only
        class="q-ml-sm"
        @click="addBankBook"
      />
    </div>

    <div
      v-for="(book, i) in bankBookList"
      class="col-12 row"
      :class="{ 'q-pt-lg': i !== 0 }"
      :key="i"
    >
      <q-separator
        v-if="i > 0"
        class="full-width"
        style="padding-block: 0.01px"
        spaced="lg"
      />
      <span class="col-12 app-text-muted-2 flex justify-between items-center">
        {{ `${$t('branch.form.bankAccountNo')} ${i + 1}` }}
        <div class="row items-center">
          <div style="height: 30.8px" />
          {{ $t('branch.form.bankAccountStatus') }}
          <ToggleButton
            id="toggle-bank-status"
            :disable="readonly"
            class="q-ml-md"
            v-model="book.currentlyUse"
          />
          <q-separator
            v-if="bankBookList.length !== 1 && !readonly"
            vertical
            spaced="lg"
          />
          <DeleteButton
            v-if="bankBookList.length !== 1 && !readonly"
            id="btn-delete-bank"
            icon-only
            @click="
              () => {
                deleteItem(bankBookList, i);
                bankQrUrl[i] = '';
              }
            "
          />
        </div>
      </span>

      <div
        class="bordered q-mr-sm rounded"
        :class="{ 'cursor-pointer': !readonly }"
      >
        <ImageHover
          :img="book.bankUrl"
          @view="() => $emit('viewQr', i)"
          @edit="
            () => {
              $emit('editQr', i);
            }
          "
          icon="mdi-qrcode"
          color="gray"
          bg-color="white"
        />
      </div>
      <div class="col">
        <div class="row q-col-gutter-sm">
          <q-select
            outlined
            clearable
            use-input
            emit-value
            fill-input
            map-options
            hide-bottom-space
            option-value="value"
            input-debounce="0"
            option-label="label"
            class="col-12 col-md-4"
            autocomplete="off"
            :dense="dense"
            :label="$t('branch.form.bank')"
            :options="bankBookOptions"
            :readonly="readonly"
            :hide-dropdown-icon="readonly"
            for="select-bankbook"
            :model-value="readonly ? book.bankName || '-' : book.bankName"
            @update:model-value="
              (v) => (typeof v === 'string' ? (book.bankName = v) : '')
            "
            @filter="bankBoookFilter"
            @clear="book.bankName = ''"
          >
            <template v-slot:option="scope">
              <q-item
                v-if="scope.opt"
                v-bind="scope.itemProps"
                class="row items-center"
              >
                <q-item-section avatar>
                  <q-img
                    :src="`/img/bank/${scope.opt.value}.png`"
                    class="bordered"
                    style="border-radius: 50%"
                  />
                </q-item-section>
                <q-item-section>
                  {{ scope.opt.label }}
                </q-item-section>
              </q-item>
            </template>

            <template v-slot:selected-item="scope">
              <q-item-section
                v-if="scope.opt && book.bankName"
                avatar
                class="q-py-sm"
              >
                <q-img
                  :src="`/img/bank/${scope.opt.value}.png`"
                  class="bordered"
                  style="border-radius: 50%"
                />
              </q-item-section>
            </template>

            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  {{ $t('general.noData') }}
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <q-input
            outlined
            for="input-bankbook"
            class="col-12 col-md-4"
            hide-bottom-space
            :dense="dense"
            :readonly="readonly"
            :label="$t('branch.form.bankAccountNumber')"
            :maxlength="15"
            :model-value="
              readonly ? book.accountNumber || '-' : book.accountNumber
            "
            @update:model-value="
              (v) => (typeof v === 'string' ? (book.accountNumber = v) : '')
            "
          />
          <q-input
            outlined
            for="input-bankbook"
            class="col-md-4 col-12"
            hide-bottom-space
            :dense="dense"
            :readonly="readonly"
            :label="$t('branch.form.bankBranch')"
            :model-value="readonly ? book.bankBranch || '-' : book.bankBranch"
            @update:model-value="
              (v) => (typeof v === 'string' ? (book.bankBranch = v) : '')
            "
          />
          <!--         :rules="[
          (val: string) =>
            (val.length >= 7 && val.length <= 13) ||
            $t('form.error.please', {
              msg: $t('branch.form.bankAccountNumber'),
            }),
        ]" -->

          <q-input
            outlined
            for="input-bankbook"
            class="col-12 col-md-4"
            hide-bottom-space
            :dense="dense"
            :readonly="readonly"
            :label="$t('branch.form.bankAccountName')"
            :model-value="readonly ? book.accountName || '-' : book.accountName"
            @update:model-value="
              (v) => (typeof v === 'string' ? (book.accountName = v) : '')
            "
          />
          <q-select
            outlined
            clearable
            use-input
            fill-input
            emit-value
            map-options
            hide-selected
            hide-bottom-space
            option-value="value"
            input-debounce="0"
            option-label="label"
            class="col-12 col-md-4"
            autocomplete="off"
            :dense="dense"
            :label="$t('branch.form.bankAccountType')"
            :options="accountTypeOptions"
            :readonly="readonly"
            :hide-dropdown-icon="readonly"
            for="select-bankbook"
            :model-value="readonly ? book.accountType || '-' : book.accountType"
            @update:model-value="
              (v) => (typeof v === 'string' ? (book.accountType = v) : '')
            "
            @filter="accountTypeFilter"
            @clear="book.accountType = ''"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  {{ $t('general.noData') }}
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss"></style>
