<script setup lang="ts">
import { QSelect } from 'quasar';
import { CustomerBranch } from 'stores/customer/types';
import { selectFilterOptionRefMod } from 'stores/utils';
import { onMounted, ref, watch } from 'vue';
import {
  EditButton,
  DeleteButton,
  SaveButton,
  UndoButton,
} from 'components/button';

const optionsBranch = defineModel<{ id: string; name: string }[]>(
  'optionsBranch',
  { default: [] },
);

// employee
const customerBranch = defineModel<{
  id: string;
  address: string;
  addressEN: string;
  provinceId: string;
  districtId: string;
  subDistrictId: string;
  zipCode: string;
}>('customerBranch');

const nrcNo = defineModel<string>('nrcNo');
const code = defineModel<string>('code');

defineProps<{
  noAction?: boolean;
  title?: string;
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  typeCustomer?: string;
  employee?: boolean;
  employeeOwnerOption?: CustomerBranch[];
  prefixId: string;
  showBtnSave?: boolean;
}>();

defineEmits<{
  (e: 'filterOwnerBranch', val: string, update: void): void;
  (e: 'save'): void;
  (e: 'undo'): void;
  (e: 'delete'): void;
  (e: 'edit'): void;
}>();

const branchOptions = ref<Record<string, unknown>[]>([]);
let branchFilter: (
  value: string,
  update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void,
) => void;

watch(
  () => optionsBranch.value,
  () => {
    branchFilter = selectFilterOptionRefMod(
      optionsBranch,
      branchOptions,
      'name',
    );
  },
);

onMounted(() => {
  branchFilter = selectFilterOptionRefMod(optionsBranch, branchOptions, 'name');
});
</script>

<template>
  <div class="row col-12">
    <div
      class="col-12 items-center row justify-between q-pb-sm text-weight-bold text-body1"
    >
      <div>
        <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)"
        />
        {{ $t(`${title}`) }}
      </div>

      <!-- v-if="!readonly" -->
      <div class="row" v-if="!noAction">
        <UndoButton
          v-if="!readonly && !showBtnSave"
          id="btn-info-basic-undo"
          icon-only
          @click="$emit('undo')"
          type="button"
        />
        <SaveButton
          v-if="!readonly"
          id="btn-info-basic-save"
          icon-only
          @click="$emit('save')"
          type="submit"
        />
        <EditButton
          v-if="readonly && !showBtnSave"
          id="btn-info-basic-edit"
          icon-only
          @click="$emit('edit')"
          type="button"
        />
        <DeleteButton
          v-if="readonly && !showBtnSave"
          id="btn-info-basic-delete"
          icon-only
          @click="$emit('delete')"
          type="button"
        />
      </div>
    </div>

    <div class="col-12 row" style="gap: var(--size-2)">
      <q-select
        :id="`${prefixId}-select-employer-branch`"
        :for="`${prefixId}-select-employer-branch`"
        :use-input="!customerBranch"
        input-debounce="0"
        :hide-dropdown-icon="readonly"
        :dense="dense"
        outlined
        :readonly="readonly"
        hide-bottom-space
        class="col-12"
        :label="$t('customer.form.branchCode')"
        v-model="customerBranch"
        :option-value="
          (v) => ({
            id: v.id,
            address: v.address,
            addressEN: v.addressEN,
            provinceId: v.provinceId,
            districtId: v.districtId,
            subDistrictId: v.subDistrictId,
            zipCode: v.zipCode,
          })
        "
        emit-value
        map-options
        :options="employeeOwnerOption"
        @filter="(val, update) => $emit('filterOwnerBranch', val, update)"
        :rules="[
          (val: string) =>
            !!val ||
            $t('form.error.selectField', {
              field: $t('customerEmployee.branch'),
            }),
        ]"
      >
        <template v-slot:option="scope">
          <q-item
            v-if="scope.opt"
            v-bind="scope.itemProps"
            class="row items-start col-12 no-padding"
          >
            <div class="q-ma-sm">
              <i class="isax isax-frame5" style="color: var(--brand-1)" />
            </div>
            <div class="q-mt-sm">
              <div>
                {{ scope.opt.code }} {{ $t('general.name') }}:

                <template v-if="scope.opt.customer.customerType === 'CORP'">
                  {{
                    $i18n.locale === 'eng'
                      ? scope.opt.registerName
                      : scope.opt.registerNameEN
                  }}
                </template>
                <template v-else>
                  {{
                    $i18n.locale === 'eng'
                      ? scope.opt.customer.firstNameEN ||
                        '-' + ' ' + scope.opt.customer.lastNameEN ||
                        ''
                      : scope.opt.customer.firstName ||
                        '-' + ' ' + scope.opt.customer.lastName ||
                        ''
                  }}
                </template>
              </div>

              <div class="text-caption app-text-muted-2 q-mb-xs">
                <div v-if="scope.opt.customer" class="col column">
                  <span>
                    {{ $t('customerEmployee.form.employerSelect.branchName') }}:
                    {{
                      $i18n.locale === 'eng'
                        ? scope.opt.registerNameEN
                        : scope.opt.registerName
                    }}
                  </span>
                  <span>
                    {{ $t('customerEmployee.form.employerSelect.branchName') }}:
                    {{
                      $i18n.locale === 'eng'
                        ? scope.opt.customer.firstNameEN ||
                          '-' + ' ' + scope.opt.customer.lastNameEN
                        : scope.opt.customer.firstName ||
                          '-' + ' ' + scope.opt.customer.lastName
                    }}
                  </span>
                </div>
                <div v-if="scope.opt.province" class="col">
                  {{ $t('general.address') }}
                  {{
                    $i18n.locale === 'eng'
                      ? `${scope.opt.addressEN || ''} ${scope.opt.subDistrict.nameEN || ''} ${scope.opt.district.nameEN || ''} ${scope.opt.province.nameEN || ''}`
                      : `${scope.opt.address || ''} ${scope.opt.subDistrict.name || ''} ${scope.opt.district.name || ''} ${scope.opt.province.name || ''}`
                  }}
                  {{ scope.opt.subDistrict?.zipCode || '' }}
                </div>
              </div>
            </div>
          </q-item>
          <q-separator class="q-mx-sm" />
        </template>

        <template v-slot:selected-item="scope">
          <div
            v-if="scope.opt"
            class="row items-center no-wrap"
            style="width: 1px"
          >
            <div class="q-mr-sm">
              {{ scope.opt.code }}
              {{ $t('customerEmployee.form.employerSelect.branchName') }}:
              {{
                $i18n.locale === 'eng'
                  ? scope.opt.registerNameEN
                  : scope.opt.registerName
              }}
            </div>
            <div
              class="text-caption app-text-muted-2"
              v-if="scope.opt.customer && scope.opt.province"
            >
              {{ $t('customerEmployee.form.employerSelect.branchName') }}:
              {{
                $i18n.locale === 'eng'
                  ? scope.opt.customer.firstNameEN ||
                    '-' + ' ' + scope.opt.customer.lastNameEN
                  : scope.opt.customer.firstName ||
                    '-' + ' ' + scope.opt.customer.lastName
              }}

              {{ $t('general.address') }}
              {{
                $i18n.locale === 'eng'
                  ? `${scope.opt.addressEN || ''} ${scope.opt.subDistrict.nameEN || ''} ${scope.opt.district.nameEN || ''} ${scope.opt.province.nameEN || ''}`
                  : `${scope.opt.address || ''} ${scope.opt.subDistrict.name || ''} ${scope.opt.district.name || ''} ${scope.opt.province.name || ''}`
              }}
              {{ scope.opt.subDistrict?.zipCode || '' }}
              <q-tooltip v-if="scope.opt.customer && scope.opt.province">
                {{ $t('customerEmployee.form.employerSelect.branchName') }}:
                {{
                  $i18n.locale === 'eng'
                    ? scope.opt.customer.firstNameEN ||
                      '-' + ' ' + scope.opt.customer.lastNameEN
                    : scope.opt.customer.firstName ||
                      '-' + ' ' + scope.opt.customer.lastName
                }}

                {{ $t('general.address') }}
                {{
                  $i18n.locale === 'eng'
                    ? `${scope.opt.addressEN || ''} ${scope.opt.subDistrict.nameEN || ''} ${scope.opt.district.nameEN || ''} ${scope.opt.province.nameEN || ''}`
                    : `${scope.opt.address || ''} ${scope.opt.subDistrict.name || ''} ${scope.opt.district.name || ''} ${scope.opt.province.name || ''}`
                }}
                {{ scope.opt.zipCode || '' }}
              </q-tooltip>
            </div>
          </div>
        </template>

        <template v-slot:append>
          <q-icon
            v-if="!readonly && customerBranch"
            name="mdi-close-circle"
            @click.stop="customerBranch = undefined"
            class="cursor-pointer clear-btn"
          />
        </template>
      </q-select>

      <q-input
        :for="`${prefixId}-input-code`"
        :dense="dense"
        outlined
        hide-bottom-space
        :readonly="readonly"
        :disable="!readonly"
        class="col-3"
        :label="$t('customerEmployee.form.employeeCode')"
        v-model="code"
      />

      <q-input
        :for="`${prefixId}-input-nrc-no`"
        :dense="dense"
        outlined
        hide-bottom-space
        :readonly="readonly"
        class="col-6"
        :label="$t('customerEmployee.form.nrcNo')"
        :model-value="readonly ? nrcNo || '-' : nrcNo"
        @update:model-value="(v) => (typeof v === 'string' ? (nrcNo = v) : '')"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.clear-btn {
  opacity: 50%;
  transition: opacity 0.2s ease-in-out;
  &:hover {
    opacity: 100%;
  }
}
</style>
