<script lang="ts" setup>
import { ref, watch } from 'vue';
import { QSelect } from 'quasar';
import { selectFilterOptionRefMod } from 'stores/utils';
import { AddressForm } from 'components/form';
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 middleName = defineModel<string>('middleName', { default: '' });
const middleNameEn = defineModel<string>('middleNameEn', { default: '' });

const workplaceEN = defineModel<string>('workplaceEn', { default: '' });
const addressEN = defineModel('addressEN', { default: '' });
const street = defineModel('street', { default: '' });
const streetEN = defineModel('streetEN', { default: '' });
const moo = defineModel('moo', { default: '' });
const mooEN = defineModel('mooEN', { default: '' });
const soi = defineModel('soi', { default: '' });
const soiEN = defineModel('soiEN', { default: '' });
const provinceId = defineModel<string | null | undefined>('provinceId');
const districtId = defineModel<string | null | undefined>('districtId');
const subDistrictId = defineModel<string | null | undefined>('subDistrictId');
const zipCode = defineModel<string | null | undefined>('zipCode');
const sameWithEmployer = defineModel<boolean>('sameWithEmployer');
const homeCode = defineModel<string | null | undefined>('homeCode');
const employmentOffice = defineModel<string | null | undefined>(
  'employmentOffice',
);
const employmentOfficeEN = defineModel<string | null | undefined>(
  'employmentOfficeEN',
);

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

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

const religion = defineModel<string>('religion', { 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-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
            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
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col"
            :label="$t('general.nationality')"
            for="input-nationality"
            v-model="nationality"
          />

          <q-input
            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"
            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"
            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
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col-5"
            :label="$t('customer.form.firstName')"
            for="input-first-name"
            v-model="firstName"
          />

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

          <q-input
            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
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col-5"
            :label="$t('customer.form.firstNameEN')"
            for="input-first-name-en"
            v-model="firstNameEN"
            :rules="[(val) => /^[A-Za-z]+$/.test(val)]"
            :error-message="$t('form.error.letterOnly')"
          />
          <q-input
            dense
            outlined
            :readonly="readonly"
            hide-bottom-space
            class="col-5"
            :label="$t('customer.form.lastNameEN')"
            for="input-last-name-en"
            v-model="lastNameEN"
            :rules="[(val) => /^[A-Za-z]+$/.test(val)]"
            :error-message="$t('form.error.letterOnly')"
          />

          <AddressForm
            prefixId="citizen"
            v-model:homeCode="homeCode"
            v-model:employmentOffice="employmentOffice"
            v-model:employmentOfficeEN="employmentOfficeEN"
            v-model:address="address"
            v-model:addressEN="addressEN"
            v-model:street="street"
            v-model:streetEN="streetEN"
            v-model:moo="moo"
            v-model:mooEN="mooEN"
            v-model:soi="soi"
            v-model:soiEN="soiEN"
            v-model:province-id="provinceId"
            v-model:district-id="districtId"
            v-model:sub-district-id="subDistrictId"
            hide-title
            dense
          />

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

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