<script setup lang="ts">
import useUserStore from 'stores/user';
import { selectFilterOptionRefMod } from 'stores/utils';
import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { isRoleInclude } from 'src/stores/utils';

const userStore = useUserStore();
const { t } = useI18n();

const hqId = defineModel<string | null | undefined>('hqId');
const brId = defineModel<string | null | undefined>('brId');
const userType = defineModel<string>('userType');
const userRole = defineModel<string>('userRole');
const username = defineModel<string | null | undefined>('username');
const userCode = defineModel<string>('userCode');

const props = defineProps<{
  title?: string;
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  separator?: boolean;
  usernameReadonly?: boolean;
}>();

async function selectHq(id: string) {
  if (!id) return;
  brId.value = '';
  userStore.userOption.brOpts = [];
  await userStore.fetchBrOption(id);
  if (userStore.userOption.brOpts.length === 1) {
    brId.value = userStore.userOption.brOpts[0].value;
  }
  brFilter = selectFilterOptionRefMod(
    ref(userStore.userOption.brOpts),
    brOptions,
    'label',
  );
}

const hqOptions = ref<Record<string, unknown>[]>([]);
const hqFilter = selectFilterOptionRefMod(
  ref(userStore.userOption.hqOpts),
  hqOptions,
  'label',
);

const brOptions = ref<Record<string, unknown>[]>([]);
let brFilter = selectFilterOptionRefMod(
  ref(userStore.userOption.brOpts),
  brOptions,
  'label',
);

const userTypeOptions = ref<Record<string, unknown>[]>([]);
const userTypeFilter = selectFilterOptionRefMod(
  ref(
    userStore.userOption.userTypeOpts.map((v) => ({
      label: t(`personnel.${v.label}`),
      value: v.value,
    })),
  ),
  userTypeOptions,
  'label',
);

const roleOptions = ref<Record<string, unknown>[]>([]);
const roleFilter = selectFilterOptionRefMod(
  ref(userStore.userOption.roleOpts),
  roleOptions,
  'label',
);

onMounted(async () => {
  if (userStore.userOption.hqOpts[0].value && !props.readonly) {
    await userStore.fetchBrOption(userStore.userOption.hqOpts[0].value);
    if (userStore.userOption.brOpts.length === 1) {
      brId.value = userStore.userOption.brOpts[0].value;
    }
    brFilter = selectFilterOptionRefMod(
      ref(userStore.userOption.brOpts),
      brOptions,
      'label',
    );
  }
});

watch(
  () => hqId.value,
  async (v) => {
    if (v) {
      userStore.userOption.brOpts = [];
      await userStore.fetchBrOption(v);
      brFilter = selectFilterOptionRefMod(
        ref(userStore.userOption.brOpts),
        brOptions,
        'label',
      );
    }
  },
);
</script>
<template>
  <div class="row col-12">
    <div class="col-12 q-pb-sm text-weight-bold text-body1">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-xs"
        color="info"
        name="mdi-office-building-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`${title}`) }}
    </div>

    <div class="col-12 row q-col-gutter-sm">
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        :disable="isRoleInclude(['branch_manager']) && !readonly"
        v-model="hqId"
        for="select-hq-id"
        input-debounce="0"
        option-label="label"
        option-value="value"
        class="col-md-2 col-12"
        :dense="dense"
        :readonly="readonly"
        :hide-dropdown-icon="readonly"
        :label="$t('branch.form.code')"
        :options="hqOptions"
        :rules="[
          (val: string) =>
            !!val ||
            $t('form.error.selectField', { field: $t('branch.form.code') }),
        ]"
        @update:model-value="(val: string) => selectHq(val)"
        @filter="hqFilter"
        @clear="
          () => {
            (hqId = ''), (brId = '');
          }
        "
      >
        <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-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        for="select-br-id"
        input-debounce="0"
        option-label="label"
        option-value="value"
        class="col-md-2 col-12"
        :disable="isRoleInclude(['branch_manager']) && !readonly"
        :dense="dense"
        :readonly="readonly"
        :hide-dropdown-icon="readonly"
        :label="$t('branch.form.codeBranch')"
        :options="brOptions"
        @filter="brFilter"
        :model-value="readonly ? brId || '-' : brId"
        @update:model-value="(v) => (typeof v === 'string' ? (brId = v) : '')"
        @clear="brId = ''"
      >
        <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
        for="input-username"
        :dense="dense"
        outlined
        :readonly="usernameReadonly"
        emit-value
        map-options
        options-dense
        hide-bottom-space
        class="col-md col-12"
        :label="$t('personnel.form.username')"
        v-model="username"
        :rules="[
          (val: string) => val.length > 2 || $t('form.error.required'),
          (val: string) =>
            (val.length > 0 && /^[a-zA-Z0-9]+$/.test(val)) ||
            $t('form.error.letterAndNumOnly'),
        ]"
      />

      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col"
        v-model="userType"
        input-debounce="0"
        option-value="value"
        option-label="label"
        for="select-user-type"
        :dense="dense"
        :readonly="readonly"
        :hide-dropdown-icon="readonly"
        :label="$t('personnel.form.userType')"
        :options="userTypeOptions"
        :rules="[
          (val: string) =>
            !!val ||
            $t('form.error.selectField', {
              field: $t('personnel.form.userType'),
            }),
        ]"
        @filter="userTypeFilter"
      >
        <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-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col"
        input-debounce="0"
        option-label="label"
        option-value="value"
        for="select-user-role"
        :dense="dense"
        v-model="userRole"
        :readonly="readonly"
        :hide-dropdown-icon="readonly"
        :label="$t('personnel.form.userRole')"
        :options="roleOptions"
        :rules="[
          (val: string) =>
            !!val ||
            $t('form.error.selectField', {
              field: $t('personnel.form.userRole'),
            }),
        ]"
        @filter="roleFilter"
      >
        <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
      id="input-user-code"
      :dense="dense"
      :outlined="readonly ? false : outlined"
      :borderless="readonly"
      readonly
      hide-bottom-space
      class="col-3"
      :label="$t('formDialogInputUserCode')"
      v-model="userCode"
    /> -->
    </div>
  </div>
</template>
