<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;
    onCreate?: 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',
    );
  },
);
</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' && !onCreate"
        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"
          :model-value="optionStore.mapOption(businessType)"
        />
      </div>

      <div
        v-if="customerType === 'PERS' && !onCreate"
        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"
          :model-value="optionStore.mapOption(businessType)"
        />
      </div>

      <div v-if="!onCreate" 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"
          :model-value="optionStore.mapOption(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>
</template>
