<script setup lang="ts">
import { QSelect } from 'quasar';
import { onMounted, ref, watch, capitalize } from 'vue';
import { formatNumberDecimal, selectFilterOptionRefMod } from 'stores/utils';
import { calculateAge, disabledAfterToday } from 'src/utils/datetime';

import useOptionStore from 'src/stores/options';
import DatePicker from 'src/components/shared/DatePicker.vue';

const props = defineProps<{
  index: string;
  code?: string;
  readonly?: boolean;
  prefixId?: string;
  customerType?: 'PERS' | 'CORP';
}>();

const optionStore = useOptionStore();

// PERS
const citizenId = defineModel<string | undefined>('citizenId', {
  required: true,
});
const prefixName = defineModel<string | null>('prefixName');
const firstName = defineModel<string>('firstName');
const lastName = defineModel<string>('lastName');
const firstNameEN = defineModel<string>('firstNameEN');
const lastNameEN = defineModel<string>('lastNameEN');
const gender = defineModel<string>('gender');
const birthDate = defineModel<Date | string | null>('birthDate');

// CORP
const customerName = defineModel<string>('customerName');
const legalPersonNo = defineModel<string | undefined>('legalPersonNo', {
  required: true,
});
const branchCode = defineModel<string | undefined>('branchCode', {
  required: true,
});
const registerName = defineModel<string | undefined>('registerName', {
  required: true,
});
const registerNameEN = defineModel<string | undefined>('registerNameEN', {
  required: true,
});
const registerDate = defineModel<Date | null>('registerDate');
const authorizedCapital = defineModel<string>('authorizedCapital', {
  default: '0',
});

// both
const telephoneNo = defineModel<string>('telephoneNo');
const codeCustomer = defineModel<string | undefined>('codeCustomer', {
  required: true,
});

const prefixNameOptions = ref<Record<string, unknown>[]>([]);
let prefixNameFilter: (
  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',
    );
  },
);

watch(
  () => prefixName.value,
  (v) => {
    if (props.readonly) return;
    if (v === 'mr') gender.value = 'male';
    else if (v !== '') gender.value = 'female';
  },
);
</script>

<template>
  <div class="row q-col-gutter-sm">
    <template v-if="customerType === 'CORP'">
      <div class="col-12 row q-col-gutter-sm">
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-5"
          :label="$t('customer.form.employerName')"
          for="input-legal-person-no"
          v-model="customerName"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />

        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md"
          :label="$t('customer.form.legalPersonCode')"
          for="input-legal-person-code"
          v-model="legalPersonNo"
          mask="#############"
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
            (val) =>
              (val && val.length === 13 && /[0-9]+/.test(val)) ||
              $t('form.error.invalidCustomeMessage', {
                msg: $t('form.error.requireLength', { msg: 13 }),
              }),
          ]"
        />

        <q-input
          dense
          outlined
          hide-bottom-space
          class="col-12 col-md"
          for="input-customer-code"
          :disable="!readonly"
          :readonly="readonly"
          :label="$t('customer.form.customerCode')"
          :model-value="legalPersonNo"
        />

        <q-input
          dense
          outlined
          hide-bottom-space
          class="col-12 col-md"
          for="input-branch-code"
          :label="$t('customer.form.branchCode')"
          :disable="!readonly"
          :readonly="readonly"
          :model-value="branchCode"
        />
      </div>

      <div class="col-12 row q-col-gutter-sm">
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-6"
          :label="$t('customer.form.registerName')"
          for="input-register-name"
          v-model="registerName"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />

        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-6"
          label="Company name"
          for="input-register-name-en"
          v-model="registerNameEN"
          :rules="[
            (val: string) => !!val || $t('form.error.required'),
            (val: string) =>
              /^[0-9A-Za-z\s.,]+$/.test(val) || $t('form.error.letterOnly'),
          ]"
        />
      </div>

      <div class="col-12 row q-col-gutter-sm">
        <DatePicker
          v-model="registerDate"
          class="col-6 col-md-2"
          :id="`${prefixId}-input-register-date`"
          :label="$t('customer.form.registerDate')"
          :readonly="readonly"
          clearable
        />
        <q-input
          dense
          outlined
          type="text"
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-2"
          :label="$t('customer.form.authorizedCapital')"
          for="input-authorized-capital"
          :model-value="
            !readonly
              ? authorizedCapital
              : formatNumberDecimal(+authorizedCapital, 2)
          "
          @update:model-value="
            (v) => {
              authorizedCapital = `${v}`;
            }
          "
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-3"
          :label="$t('customer.form.headQuarters.telephoneNo')"
          for="input-first-name-en"
          :model-value="readonly ? telephoneNo || '-' : telephoneNo"
          @update:model-value="
            (v) => (typeof v === 'string' ? (telephoneNo = v) : '')
          "
        >
          <template #prepend>
            <q-icon
              size="xs"
              name="mdi-phone-outline"
              class="cursor-pointer"
              color="primary"
            />
          </template>
        </q-input>
      </div>
    </template>

    <template v-if="customerType === 'PERS'">
      <div class="col-7 row q-col-gutter-sm">
        <q-input
          dense
          outlined
          hide-bottom-space
          class="col-12 col-md-5"
          for="input-customer-code"
          :disable="!readonly"
          :readonly="readonly"
          :label="$t('customer.form.customerCode')"
          :model-value="codeCustomer"
        />

        <q-input
          dense
          outlined
          :disable="index !== '0' && !readonly"
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-7"
          :label="$t('customer.form.cardNumber')"
          for="input-legal-person-no"
          v-model="citizenId"
          mask="#############"
          :rules="[
            (val) => (val && val.length > 0) || $t('form.error.required'),
            (val) =>
              (val && val.length === 13 && /[0-9]+/.test(val)) ||
              $t('form.error.invalidCustomeMessage', {
                msg: $t('form.error.requireLength', { msg: 13 }),
              }),
          ]"
        />
      </div>

      <div class="col-9 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-md-2 col-6"
          dense
          :readonly="readonly"
          :options="prefixNameOptions"
          :for="`${prefixId}-select-prefix-name`"
          :label="$t('personnel.form.prefixName')"
          @filter="prefixNameFilter"
          :model-value="readonly ? prefixName || '-' : prefixName"
          @update:model-value="
            (v) => (typeof v === 'string' ? (prefixName = v) : '')
          "
          @clear="prefixName = ''"
        >
          <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="`${prefixId}-input-first-name`"
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          :label="$t('personnel.form.firstName')"
          v-model="firstName"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />
        <q-input
          :for="`${prefixId}-input-last-name`"
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          :label="$t('personnel.form.lastName')"
          v-model="lastName"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />
      </div>

      <div class="col-9 row q-col-gutter-sm">
        <q-input
          :for="`${prefixId}-input-first-name`"
          dense
          outlined
          hide-bottom-space
          :readonly="readonly"
          :disable="!readonly"
          class="col-md-2 col-6"
          label="Title"
          :model-value="
            readonly
              ? capitalize(prefixName || '') || '-'
              : capitalize(prefixName || '')
          "
          @update:model-value="
            (v) => (typeof v === 'string' ? (prefixName = v) : '')
          "
          @clear="prefixName = ''"
        />

        <q-input
          :for="`${prefixId}-input-first-name`"
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          label="Name"
          v-model="firstNameEN"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />
        <q-input
          :for="`${prefixId}-input-last-name`"
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col"
          label="Surname"
          v-model="lastNameEN"
          :rules="[(val: string) => !!val || $t('form.error.required')]"
        />
      </div>

      <div class="row col-9 q-col-gutter-sm">
        <q-input
          :for="`${prefixId}-input-telephone`"
          dense
          outlined
          :readonly="readonly"
          class="col-md col-6"
          :label="$t('form.telephone')"
          :mask="readonly ? '' : '##########'"
          :model-value="readonly ? telephoneNo || '-' : telephoneNo"
          @update:model-value="
            (v) => (typeof v === 'string' ? (telephoneNo = v) : '')
          "
          @clear="telephoneNo = ''"
        >
          <template #prepend>
            <q-icon
              size="xs"
              name="mdi-phone-outline"
              class="cursor-pointer"
              color="primary"
            />
          </template>
        </q-input>
        <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-md-2 col-6"
          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>

        <DatePicker
          v-model="birthDate"
          class="col-md col-6"
          :id="`${prefixId}-input-birth-date`"
          :readonly="readonly"
          :label="$t('form.birthDate')"
          :disabled-dates="disabledAfterToday"
          :rules="[
            (val: string) =>
              !!val ||
              $t('form.error.selectField', { field: $t('form.birthDate') }),
          ]"
        />

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