<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';
import DatePicker from '../shared/DatePicker.vue';
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';
  orc?: boolean;
}>();
defineEmits<{
  (e: 'save'): void;
  (e: 'edit'): void;
  (e: 'delete'): void;
  (e: 'cancel'): void;
}>();

const optionStore = useOptionStore();
const namePrefix = defineModel<string | null>('namePrefix');
const birthDate = defineModel<Date | string | null>('birthDate');
const gender = defineModel<string>('gender');

const address = defineModel<string>('address');
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 citizenId = defineModel<string | undefined>('citizenId', {
  required: true,
});
const nationality = defineModel<string>('nationality');

const religion = defineModel<string>('religion');

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-mb-sm">
    <template v-if="orc">
      <div class="row" style="gap: 10px">
        <div class="col-4 flex flex-center">
          <q-img
            src="/images/customer-CORP-avartar.png"
            width="80px"
            height="80px"
          ></q-img>
        </div>
        <div class="col row" style="gap: 10px">
          <q-input
            lazy-rules="ondemand"
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col-12"
            :label="$t('customer.form.citizenId')"
            for="input-citizen-id"
            v-model="citizenId"
          />

          <DatePicker
            :label="$t('form.birthDate')"
            v-model="birthDate"
            class="col-12"
            :id="`${prefixId}-input-birth-date`"
            :readonly="readonly"
            clearable
          />

          <q-input
            lazy-rules="ondemand"
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col"
            :label="$t('general.nationality')"
            for="input-nationality"
            v-model="nationality"
          />

          <q-input
            lazy-rules="ondemand"
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col"
            :label="$t('customer.form.religion')"
            for="input-religion"
            v-model="religion"
          />

          <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"
            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 = ''"
          >
            <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="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-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 = ''"
          >
            <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-5"
            :label="$t('customer.form.firstName')"
            for="input-first-name"
            v-model="firstName"
          />

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

          <q-input
            lazy-rules="ondemand"
            dense
            outlined
            :disable="!readonly"
            :readonly="readonly"
            hide-bottom-space
            class="col-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-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-5"
            :label="$t('customer.form.lastNameEN')"
            for="input-last-name-en"
            v-model="lastNameEN"
          />

          <q-input
            lazy-rules="ondemand"
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col-12"
            :label="$t('general.address')"
            for="input-address"
            v-model="address"
          />
          <DatePicker
            :label="$t('customer.form.issueDate')"
            v-model="firstName"
            class="col-6"
            :id="`${prefixId}-input-issue-date`"
            :readonly="readonly"
            clearable
          />

          <DatePicker
            :label="$t('customer.form.passportExpiryDate')"
            v-model="firstName"
            class="col-6"
            :id="`${prefixId}-input-passport-expiry-date`"
            :readonly="readonly"
            clearable
          />
        </div>
      </div>
    </template>
  </div>
</template>
