<script lang="ts" setup>
import { ref, watch } from 'vue';
import { QSelect } from 'quasar';
import { selectFilterOptionRefMod } from 'stores/utils';
import { getRole } from 'src/services/keycloak';
import useOptionStore from 'stores/options';
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
const { locale } = useI18n();

import {
  dateFormat,
  calculateAge,
  parseAndFormatDate,
  disabledAfterToday,
} from 'src/utils/datetime';

import {
  SaveButton,
  EditButton,
  DeleteButton,
  UndoButton,
} from 'components/button';
defineProps<{
  prefixId?: string;
  outlined?: boolean;
  readonly?: boolean;
  create?: boolean;
  actionDisabled?: boolean;
  customerType?: 'CORP' | 'PERS';
}>();
defineEmits<{
  (e: 'save'): void;
  (e: 'edit'): void;
  (e: 'delete'): void;
  (e: 'cancel'): void;
}>();

const optionStore = useOptionStore();
const code = defineModel<string>('code', { required: true });
const namePrefix = defineModel<string | null>('namePrefix');
const birthDate = defineModel<Date | string | null>('birthDate');
const gender = defineModel<string>('gender');

const firstName = defineModel<string>('firstName', { required: true });
const lastName = defineModel<string>('lastName', { required: true });
const firstNameEN = defineModel<string>('firstNameEn', { required: true });
const lastNameEN = defineModel<string>('lastNameEn', { required: true });

const registeredBranchId = defineModel<string>('registeredBranchId', {
  required: true,
});

const branchOptions = defineModel<{ id: string; name: string }[]>(
  'branchOptions',
  { default: [] },
);
const filteredBranchOptions = ref<Record<string, unknown>[]>([]);

let branchFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

onMounted(() => {
  branchFilter = selectFilterOptionRefMod(
    branchOptions,
    filteredBranchOptions,
    'name',
  );
});

watch(
  () => branchOptions.value,
  () => {
    branchFilter = selectFilterOptionRefMod(
      branchOptions,
      filteredBranchOptions,
      'name',
    );
  },
);

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

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

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

onMounted(() => {
  prefixNameFilter = selectFilterOptionRefMod(
    ref(optionStore.globalOption?.prefix),
    prefixNameOptions,
    'label',
  );
  genderFilter = selectFilterOptionRefMod(
    ref(optionStore.globalOption?.gender),
    genderOptions,
    'label',
  );
});

watch(
  () => optionStore.globalOption,
  () => {
    prefixNameFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.prefix),
      prefixNameOptions,
      'label',
    );
    genderFilter = selectFilterOptionRefMod(
      ref(optionStore.globalOption.gender),
      genderOptions,
      'label',
    );
  },
);

function formatCode(input: string | undefined, type: 'code' | 'number') {
  if (!input) return;
  return input.slice(...(type === 'code' ? [0, -6] : [-6]));
}
</script>

<template>
  <div class="row q-col-gutter-sm q-mb-sm">
    <div class="col-12 text-weight-bold text-body1 row items-center">
      <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)"
      />
      <span>{{ $t('form.field.basicInformation') }}</span>
      <EditButton
        icon-only
        v-if="readonly && !create"
        type="button"
        @click="$emit('edit')"
        class="q-ml-auto"
        :disabled="actionDisabled"
      />
      <DeleteButton
        icon-only
        v-if="readonly && !create"
        @click="$emit('delete')"
        type="button"
        :disabled="actionDisabled"
      />
      <UndoButton
        icon-only
        v-if="!readonly && !create"
        class="q-ml-auto"
        type="button"
        :disabled="actionDisabled"
        @click="$emit('cancel')"
      />
      <SaveButton
        icon-only
        v-if="!readonly"
        :class="{ 'q-ml-auto': create }"
        @click="$emit('save')"
        type="submit"
        :disabled="actionDisabled"
      />
    </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
        dense
        class="col-12 col-md-7"
        option-value="id"
        input-debounce="0"
        option-label="name"
        lazy-rules="ondemand"
        v-model="registeredBranchId"
        :readonly="readonly"
        :options="filteredBranchOptions"
        :hide-dropdown-icon="readonly"
        :label="$t('customer.form.registeredBranch')"
        :for="`${prefixId}-input-source-nationality`"
        :rules="[
          (val) => {
            const roles = getRole() || [];
            return (
              ['admin', 'system', 'head_of_admin'].some((v) =>
                roles.includes(v),
              ) ||
              !!val ||
              $t('form.error.required')
            );
          },
        ]"
        @filter="branchFilter"
      >
        <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 class="col-12 row q-col-gutter-sm">
      <q-select
        outlined
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        input-debounce="0"
        option-label="label"
        option-value="value"
        lazy-rules="ondemand"
        hide-dropdown-icon
        class="col-12 col-md-2"
        dense
        :readonly="readonly"
        :options="prefixNameOptions"
        :for="`${prefixId}-select-prefix-name`"
        :label="$t('form.prefixName')"
        @filter="prefixNameFilter"
        :model-value="readonly ? namePrefix || '-' : namePrefix"
        @update:model-value="
          (v) => {
            typeof v === 'string' ? (namePrefix = v) : '';
          }
        "
        @clear="namePrefix = ''"
        :rules="[
          (val) => {
            const roles = getRole() || [];
            return !!val || $t('form.error.required');
          },
        ]"
      >
        <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
        lazy-rules="ondemand"
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-5"
        :label="$t('customer.form.firstName')"
        for="input-first-name"
        v-model="firstName"
        :rules="[
          (val) => {
            const roles = getRole() || [];
            return !!val || $t('form.error.required');
          },
        ]"
      />
      <q-input
        lazy-rules="ondemand"
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-5"
        :label="$t('customer.form.lastName')"
        for="input-last-name"
        v-model="lastName"
        :rules="[
          (val) => {
            const roles = getRole() || [];
            return !!val || $t('form.error.required');
          },
        ]"
      />
    </div>

    <div class="col-12 row q-col-gutter-sm">
      <q-input
        lazy-rules="ondemand"
        dense
        outlined
        :disable="!readonly"
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-2"
        :label="$t('customer.form.prefixName')"
        for="input-prefix-name"
        :model-value="
          namePrefix ? $t(`customer.form.prefix.${namePrefix}`) : '-'
        "
      />

      <q-input
        lazy-rules="ondemand"
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-5"
        :label="$t('customer.form.firstNameEN')"
        for="input-first-name-en"
        v-model="firstNameEN"
      />
      <q-input
        lazy-rules="ondemand"
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-5"
        :label="$t('customer.form.lastNameEN')"
        for="input-last-name-en"
        v-model="lastNameEN"
      />
    </div>

    <div class="col-12 row q-col-gutter-sm">
      <q-select
        outlined
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        input-debounce="0"
        option-label="label"
        option-value="value"
        lazy-rules="ondemand"
        class="col-12 col-md-2"
        dense
        :readonly="readonly"
        :options="genderOptions"
        :hide-dropdown-icon="readonly"
        :for="`${prefixId}-select-gender`"
        :label="$t('form.gender')"
        @filter="genderFilter"
        :model-value="readonly ? gender || '-' : gender"
        @update:model-value="(v) => (typeof v === 'string' ? (gender = v) : '')"
        @clear="gender = ''"
        :rules="[
          (val) => {
            const roles = getRole() || [];
            return !!val || $t('form.error.required');
          },
        ]"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              {{ $t('general.noData') }}
            </q-item-section>
          </q-item>
        </template>
      </q-select>

      <VueDatePicker
        :id="`${prefixId}-input-birth-date`"
        :for="`${prefixId}-input-birth-date`"
        utc
        autoApply
        v-model="birthDate"
        :disabled-dates="disabledAfterToday"
        :teleport="true"
        :dark="$q.dark.isActive"
        :locale="$i18n.locale === 'tha' ? 'th' : 'en'"
        :enableTimePicker="false"
        :disabled="readonly"
        class="col-12 col-md-3"
      >
        <template #year="{ value }">
          {{ $i18n.locale === 'tha' ? value + 543 : value }}
        </template>
        <template #year-overlay-value="{ value }">
          {{ $i18n.locale === 'tha' ? value + 543 : value }}
        </template>
        <template #trigger>
          <q-input
            lazy-rules="ondemand"
            :for="`${prefixId}-input-birth-date`"
            hide-bottom-space
            placeholder="DD/MM/YYYY"
            :label="$t('form.birthDate')"
            dense
            outlined
            :readonly="readonly"
            :rules="[
              (val: string) =>
                !!val || $t('selectValidate') + $t('form.birthDate'),
            ]"
            :mask="readonly ? '' : '##/##/####'"
            :model-value="
              birthDate && readonly
                ? dateFormat(birthDate)
                : dateFormat(birthDate, false, false, true)
            "
            @update:model-value="
              (v) => {
                if (v && v.toString().length === 10) {
                  const today = new Date();
                  const date = parseAndFormatDate(v, locale);
                  birthDate = date && date > today ? today : date;
                }
              }
            "
          >
            <template v-slot:prepend>
              <q-icon
                size="xs"
                name="mdi-calendar-blank-outline"
                class="cursor-pointer"
                color="primary"
              />
            </template>
          </q-input>
        </template>
      </VueDatePicker>

      <q-input
        lazy-rules="ondemand"
        :for="`${prefixId}-input-age`"
        :id="`${prefixId}-input-age`"
        dense
        outlined
        :readonly="readonly"
        :label="$t('general.age')"
        class="col-12 col-md-2"
        :model-value="
          birthDate?.toString() === 'Invalid Date' ||
          birthDate?.toString() === undefined
            ? ''
            : calculateAge(birthDate)
        "
      />
    </div>
  </div>
</template>
