<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('customer.form.group.basicInfo') }}</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-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        dense
        class="col-12 col-md-9"
        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('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('noResults') }}
            </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-1"
        dense
        :readonly="readonly"
        :options="prefixNameOptions"
        :for="`${prefixId}-select-prefix-name`"
        :label="$t('formDialogInputPrefixName')"
        @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('noResults') }}
            </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-4"
        :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-12 col-md-4"
        :label="$t('customer.form.lastName')"
        for="input-last-name"
        v-model="lastName"
      />
    </div>

    <div class="col-12 row q-col-gutter-sm">
      <q-input
        lazy-rules="ondemand"
        dense
        outlined
        disable
        :readonly="readonly"
        hide-bottom-space
        class="col-12 col-md-1"
        :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-4"
        :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-4"
        :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-2"
        dense
        :readonly="readonly"
        :options="genderOptions"
        :hide-dropdown-icon="readonly"
        :for="`${prefixId}-select-gender`"
        :label="$t('formDialogInputGender')"
        @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('noResults') }}
            </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 === 'th-th' ? 'th' : 'en'"
        :enableTimePicker="false"
        :disabled="readonly"
        class="col-2"
      >
        <template #year="{ value }">
          {{ $i18n.locale === 'th-th' ? value + 543 : value }}
        </template>
        <template #year-overlay-value="{ value }">
          {{ $i18n.locale === 'th-th' ? 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('formDialogInputBirthDate')"
            dense
            outlined
            :readonly="readonly"
            :rules="[
              (val: string) =>
                !!val || $t('selectValidate') + $t('formDialogInputBirthDate'),
            ]"
            :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('formDialogInputAge')"
        class="col-2"
        :model-value="
          birthDate?.toString() === 'Invalid Date' ||
          birthDate?.toString() === undefined
            ? ''
            : calculateAge(birthDate)
        "
      />
    </div>

    <!-- <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
      hide-selected
      hide-bottom-space
      dense
      class="col-12 col-md-4"
      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('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('noResults') }}
          </q-item-section>
        </q-item>
      </template>
    </q-select>
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      :disable="!readonly && !create"
      :readonly="readonly"
      hide-bottom-space
      class="col-12 col-md-4"
      :label="$t('customer.form.codeAbbrev')"
      for="input-abbreviation"
      :model-value="!create ? formatCode(code, 'code') : code"
      :rules="[
        (val: string) =>
          (val && val.length > 0 && /[a-zA-Z]+/.test(val)) ||
          $t('formDialogInputHqAbbreviation'),
      ]"
      @update:model-value="(v: string) => (code = v)"
    />
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      readonly
      :disable="!readonly"
      hide-bottom-space
      class="col-12 col-md-4"
      :label="$t('customer.form.codeNumber')"
      for="input-code"
      :model-value="!create ? formatCode(code, 'number') : ''"
      @update:model-value="(v: string) => (code = v)"
    />
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      hide-bottom-space
      :label="$t('customer.form.customerName')"
      v-model="customerName"
      class="col-12 col-md-4"
      :readonly="readonly"
      :for="`${prefixId}-input-company-name`"
    />
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      :readonly="readonly"
      hide-bottom-space
      :label="$t('customer.form.customerNameEN')"
      v-model="customerNameEN"
      :for="`${prefixId}-input-company-name-en`"
      class="col-12 col-md-4"
    />
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      :readonly="readonly"
      hide-bottom-space
      v-model="personName"
      :label="$t('customer.form.personName')"
      :for="`${prefixId}-input-person-name`"
      :rules="[(v: string) => !!v || $t('form.error.required')]"
      class="col-12 col-md-4"
    />
    <q-input
      lazy-rules="ondemand"
      dense
      outlined
      v-if="customerType === 'PERS'"
      :readonly="readonly"
      hide-bottom-space
      :label="$t('customer.form.taxIdentificationNumber')"
      v-model="taxNo"
      :for="`${prefixId}-input-tax-no`"
      class="col-12 col-md-4"
    /> -->
  </div>
</template>
