<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 {
  SaveButton,
  EditButton,
  DeleteButton,
  UndoButton,
} from 'components/button';

withDefaults(
  defineProps<{
    prefixId?: string;
    outlined?: boolean;
    readonly?: boolean;
    create?: boolean;
    actionDisabled?: boolean;
    customerType?: 'CORP' | 'PERS';
    hideAction?: boolean;
  }>(),
  {
    hideAction: false,
  },
);
defineEmits<{
  (e: 'save'): void;
  (e: 'edit'): void;
  (e: 'delete'): void;
  (e: 'cancel'): void;
}>();

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

const customerName = defineModel<string>('customerName');
const registerName = defineModel<string>('registerName');

const citizenId = defineModel<string>('citizenId');
const legalPersonNo = defineModel<string>('legalPersonNo');

const businessType = defineModel<'strinf'>('businessType');
const jobPosition = defineModel<'strinf'>('jobPosition');
const telephoneNo = defineModel<string>('telephoneNo');

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 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(
//   () => namePrefix.value,
//   (v) => {
//     if (v === 'mr') gender.value = 'male';
//     else gender.value = 'female';
//   },
// );

// 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">
    <div
      v-if="!hideAction"
      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('general.information', {
            msg: `${$t('customer.employer')}${
              customerType === 'CORP'
                ? $t('customer.employerLegalEntity')
                : $t('customer.employerNaturalPerson')
            }`,
          })
        }}
      </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">
      <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-6"
          option-value="id"
          input-debounce="0"
          option-label="name"
          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
        v-if="customerType === 'CORP' && !create"
        class="row col-12 q-col-gutter-sm"
      >
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-6"
          :label="$t('customer.form.customerName')"
          for="input-first-name"
          v-model="registerName"
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-3"
          :label="$t('general.taxNo')"
          for="input-first-name-en"
          v-model="legalPersonNo"
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-3"
          :label="$t('customer.table.businessTypePure')"
          for="input-first-name-en"
          v-model="businessType"
        />
      </div>

      <div
        v-if="customerType === 'PERS' && !create"
        class="row col-12 q-col-gutter-sm"
      >
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-6"
          :label="$t('customer.form.employerName')"
          for="input-first-name"
          v-model="customerName"
        />
        <q-input
          outlined
          class="col-md-3 col-6"
          hide-bottom-space
          v-model="citizenId"
          mask="#############"
          :readonly="readonly"
          dense
          :label="$t('personnel.form.citizenId')"
          for="input-citizen-id"
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-3"
          :label="$t('customer.table.businessTypePure')"
          for="input-first-name-en"
          v-model="businessType"
        />
      </div>

      <div v-if="!create" class="row col-12 q-col-gutter-sm">
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md-5"
          :label="$t('customer.form.jobPosition')"
          for="input-first-name-en"
          v-model="jobPosition"
        />
        <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"
          v-model="telephoneNo"
        >
          <template #prepend>
            <q-icon
              size="xs"
              name="mdi-phone-outline"
              class="cursor-pointer"
              color="primary"
            />
          </template>
        </q-input>
      </div>
    </div>
    <!-- <div v-if="customerType === 'CORP'" 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.customerName')"
        for="input-first-name"
        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-6"
        :label="$t('customer.form.customerNameEN')"
        for="input-first-name-en"
        v-model="customerNameEN"
        :rules="[
          (val: string) => !!val || $t('form.error.required'),
          (val: string) =>
            /^[A-Za-z]+$/.test(val) || $t('form.error.letterOnly'),
        ]"
      />
      <q-input
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-6 col-md-3"
        :label="$t('general.taxNo')"
        for="input-first-name-en"
        v-model="taxNo"
        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
        :readonly="readonly"
        hide-bottom-space
        class="col-6 col-md-3"
        :label="$t('customer.table.businessTypePure')"
        for="input-first-name-en"
        v-model="businessType"
      />
      <q-input
        dense
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-6 col-md-3"
        :label="$t('customer.form.jobPosition')"
        for="input-first-name-en"
        v-model="jobPosition"
      />
      <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"
        v-model="telephoneNo"
      >
        <template #prepend>
          <q-icon
            size="xs"
            name="mdi-phone-outline"
            class="cursor-pointer"
            color="primary"
          />
        </template>
      </q-input>
    </div>

    <div v-if="customerType === 'PERS'" class="col-12 row q-col-gutter-sm">
      <div class="col-9 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"
          option-value="id"
          input-debounce="0"
          option-label="name"
          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>
        <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-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
          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
          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');
            },
          ]"
        />

        <q-input
          dense
          outlined
          :disable="!readonly"
          readonly
          hide-bottom-space
          class="col-12 col-md-2"
          label="Title"
          for="input-prefix-name-en"
          :model-value="
            readonly
              ? capitalize(namePrefix || '') || '-'
              : capitalize(namePrefix || '')
          "
        />

        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-5"
          label="Name"
          for="input-first-name-en"
          v-model="firstNameEN"
          :rules="[
            (val: string) => !!val || $t('form.error.required'),
            (val: string) =>
              /^[A-Za-z]+$/.test(val) || $t('form.error.letterOnly'),
          ]"
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-12 col-md-5"
          label="Surname"
          for="input-last-name-en"
          v-model="lastNameEN"
          :rules="[
            (val: string) => !!val || $t('form.error.required'),
            (val: string) =>
              /^[A-Za-z]+$/.test(val) || $t('form.error.letterOnly'),
          ]"
        />

        <q-input
          outlined
          class="col-md-5 col-12"
          hide-bottom-space
          v-model="lastNameEN"
          mask="#############"
          :readonly="readonly"
          dense
          :label="$t('personnel.form.citizenId')"
          :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 }),
              }),
          ]"
          for="input-citizen-id"
        />
        <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
          :label="$t('personnel.age')"
          class="col-md col-12"
          :model-value="
            birthDate?.toString() === 'Invalid Date' ||
            birthDate?.toString() === undefined
              ? ''
              : calculateAge(birthDate)
          "
        />
      </div>

      <div class="row col-12 q-col-gutter-sm">
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md"
          :label="$t('customer.table.businessTypePure')"
          for="input-first-name-en"
          v-model="firstNameEN"
        />
        <q-input
          dense
          outlined
          :readonly="readonly"
          hide-bottom-space
          class="col-6 col-md"
          :label="$t('customer.form.jobPosition')"
          for="input-first-name-en"
          v-model="firstNameEN"
        />
        <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"
          v-model="firstNameEN"
        >
          <template #prepend>
            <q-icon
              size="xs"
              name="mdi-phone-outline"
              class="cursor-pointer"
              color="primary"
            />
          </template>
        </q-input>
      </div>
    </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"
        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"
        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
        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
        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
        dense
        outlined
        :disable="!readonly"
        readonly
        hide-bottom-space
        class="col-12 col-md-2"
        :label="$t('customer.form.prefixName')"
        for="input-prefix-name"
        :model-value="
          readonly
            ? capitalize(namePrefix || '') || '-'
            : capitalize(namePrefix || '')
        "
      />

      <q-input
        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"
        :rules="[
          (val: string) => !!val || $t('form.error.required'),
          (val: string) =>
            /^[A-Za-z]+$/.test(val) || $t('form.error.letterOnly'),
        ]"
      />
      <q-input
        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"
        :rules="[
          (val: string) => !!val || $t('form.error.required'),
          (val: string) =>
            /^[A-Za-z]+$/.test(val) || $t('form.error.letterOnly'),
        ]"
      />
    </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"
        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
            :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
        :for="`${prefixId}-input-age`"
        :id="`${prefixId}-input-age`"
        dense
        outlined
        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>
