<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import useAddressStore, {
  District,
  Province,
  SubDistrict,
} from 'stores/address';
import { EmployeeCheckupCreate } from 'stores/employee/types';
import { selectFilterOptionRefMod } from 'stores/utils';
import { QSelect } from 'quasar';
import DatePicker from '../shared/DatePicker.vue';
import {
  AddButton,
  EditButton,
  DeleteButton,
  SaveButton,
  UndoButton,
} from 'components/button';

const adrressStore = useAddressStore();

const addrOptions = reactive<{
  provinceOps: Province[];
  districtOps: District[];
  subDistrictOps: SubDistrict[];
}>({
  provinceOps: [],
  districtOps: [],
  subDistrictOps: [],
});

const currentIndex = defineModel<number>('currentIndex');
const employeeCheckup = defineModel<EmployeeCheckupCreate[]>('employeeCheckup');
const checkupTypeOption = defineModel<{ label: string; value: string }[]>(
  'checkupTypeOption',
  { required: true },
);
const medicalBenefitOption = defineModel<{ label: string; value: string }[]>(
  'medicalBenefitOption',
  { required: true },
);
const insuranceCompanyOption = defineModel<{ label: string; value: string }[]>(
  'insuranceCompanyOption',
  { required: true },
);

const tab = ref();

withDefaults(
  defineProps<{
    title?: string;
    dense?: boolean;
    outlined?: boolean;
    readonly?: boolean;
    typeCustomer?: string;
    prefixId: string;
    showBtnSave?: boolean;
    hideAction?: boolean;
  }>(),
  {
    hideAction: false,
    showBtnSave: false,
  },
);

defineEmits<{
  (e: 'save', index: number): void;
  (e: 'edit', index: number): void;
  (e: 'delete', index: number): void;
  (e: 'undo', index: number): void;
}>();

async function fetchProvince() {
  const result = await adrressStore.fetchProvince();

  if (result) addrOptions.provinceOps = result;

  provinceFilter = selectFilterOptionRefMod(
    ref(addrOptions.provinceOps),
    provinceOptions,
    'name',
  );
}

function addCheckup() {
  // const canAdd = checkTabBeforeAdd(employeeCheckup.value || []);
  const canAdd = true;
  if (canAdd) {
    employeeCheckup.value?.push({
      coverageExpireDate: null,
      coverageStartDate: null,
      insuranceCompany: '',
      medicalBenefitScheme: '',
      remark: '',
      hospitalName: '',
      provinceId: '',
      checkupResult: '',
      checkupType: '',
    });
    if (employeeCheckup.value) {
      tab.value = `tab${employeeCheckup.value.length - 1}`;
      currentIndex.value = employeeCheckup.value.length - 1;
    }
  }
}

function removeData(index: number) {
  if (!employeeCheckup.value) return;
  if (employeeCheckup.value.length === 1) return;

  employeeCheckup.value.splice(index, 1);

  if (index) if (tab.value === `tab${index}`) tab.value = `tab${index - 1}`;
  if (tab.value === `tab${employeeCheckup.value.length}`)
    tab.value = `tab${employeeCheckup.value.length - 1}`;
}

onMounted(async () => {
  await fetchProvince();
  tab.value = 'tab0';
});

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

const checkupTypeOptions = ref<Record<string, unknown>[]>([]);
const checkupTypeFilter = selectFilterOptionRefMod(
  checkupTypeOption,
  checkupTypeOptions,
  'label',
);

const medicalBenefitOptions = ref<Record<string, unknown>[]>([]);
const medicalBenefitFilter = selectFilterOptionRefMod(
  medicalBenefitOption,
  medicalBenefitOptions,
  'label',
);

const insuranceCompanyOptions = ref<Record<string, unknown>[]>([]);
const insuranceCompanyFilter = selectFilterOptionRefMod(
  insuranceCompanyOption,
  insuranceCompanyOptions,
  'label',
);
</script>

<template>
  <div class="row col-12">
    <div class="col-12 q-pb-sm text-weight-bold text-body1 row items-center">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-sm"
        color="info"
        name="mdi-hospital-box-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`customerEmployee.formHealthCheck.title`) }}
      <AddButton
        v-if="currentIndex === -1 && !hideAction"
        id="btn-add-bank"
        icon-only
        class="q-ml-sm"
        type="button"
        @click="addCheckup"
        :disabled="!(currentIndex === -1)"
      />
    </div>

    <div
      v-for="(checkup, index) in employeeCheckup"
      v-bind:key="index"
      class="col-12 row q-col-gutter-sm"
      :class="{ 'q-pt-lg': index !== 0 }"
      :id="`${prefixId}-checkup-${index}`"
    >
      <q-separator
        v-if="index > 0"
        class="full-width"
        style="padding-block: 0.1px"
        spaced="lg"
      />
      <span class="col-12 flex justify-between items-center">
        {{ $t('general.times', { number: index + 1 }) }}
        <div class="row items-center" v-if="!hideAction">
          <UndoButton
            v-if="!readonly && !!checkup.id && !checkup.statusSave"
            id="btn-info-health-undo"
            icon-only
            @click="$emit('undo', index)"
            type="button"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
          <SaveButton
            icon-only
            id="btn-info-health-save"
            v-if="!readonly && !checkup.statusSave"
            @click="$emit('save', index)"
            type="submit"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
          <EditButton
            icon-only
            id="btn-info-health-edit"
            v-if="!readonly && checkup.statusSave"
            @click="$emit('edit', index)"
            type="button"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
          <DeleteButton
            icon-only
            id="btn-info-health-delete"
            v-if="!readonly && !!checkup.id && checkup.statusSave"
            @click="$emit('delete', index)"
            type="button"
            :disabled="!(currentIndex === -1) && !(currentIndex === index)"
          />
        </div>
      </span>

      <q-input
        :dense="dense"
        outlined
        :readonly="readonly || checkup.statusSave"
        hide-bottom-space
        class="col-5"
        :label="$t('customerEmployee.formHealthCheck.result')"
        v-model="checkup.checkupResult"
      />
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-5"
        input-debounce="0"
        option-value="value"
        option-label="label"
        v-model="checkup.checkupType"
        :dense="dense"
        :readonly="readonly || checkup.statusSave"
        :options="checkupTypeOptions"
        :hide-dropdown-icon="readonly || checkup.statusSave"
        :for="`${prefixId}-select-checkup-type`"
        :label="$t('customerEmployee.formHealthCheck.checkupType')"
        @filter="checkupTypeFilter"
      >
        <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
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        option-value="id"
        input-debounce="0"
        option-label="name"
        class="col-2"
        v-model="checkup.provinceId"
        :dense="dense"
        :readonly="readonly || checkup.statusSave"
        :label="$t('form.province')"
        :hide-dropdown-icon="readonly || checkup.statusSave"
        :for="`${prefixId}-select-province`"
        :options="provinceOptions"
        @filter="provinceFilter"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              {{ $t('general.noData') }}
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <!-- @filter="provinceFilter" -->
      <q-input
        :dense="dense"
        outlined
        :readonly="readonly || checkup.statusSave"
        hide-bottom-space
        class="col-5"
        :label="$t('customerEmployee.formHealthCheck.hospital')"
        v-model="checkup.hospitalName"
        :for="`${prefixId}-input-hospital`"
      />
      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-5"
        input-debounce="0"
        option-value="value"
        option-label="label"
        v-model="checkup.medicalBenefitScheme"
        :dense="dense"
        :readonly="readonly || checkup.statusSave"
        :hide-dropdown-icon="readonly || checkup.statusSave"
        :options="medicalBenefitOptions"
        :for="`${prefixId}-select-province`"
        :label="$t('customerEmployee.formHealthCheck.medicalBenefit')"
        @filter="medicalBenefitFilter"
      >
        <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
        :label="$t('general.remark')"
        :dense="dense"
        outlined
        :readonly="readonly || checkup.statusSave"
        hide-bottom-space
        class="col-12"
        v-model="checkup.remark"
        type="textarea"
        :for="`${prefixId}-input-remark`"
      />
      <DatePicker
        :label="$t('customerEmployee.formHealthCheck.coverageStartDate')"
        v-model="checkup.coverageStartDate"
        class="col"
        :id="`${prefixId}-input-coverage-start-date`"
        :readonly="readonly || checkup.statusSave"
        clearable
      />
      <DatePicker
        :label="$t('customerEmployee.formHealthCheck.coverageExpireDate')"
        v-model="checkup.coverageExpireDate"
        class="col"
        :id="`${prefixId}-input-coverage-expire-date`"
        :readonly="readonly || checkup.statusSave"
        clearable
      />

      <q-select
        outlined
        clearable
        use-input
        fill-input
        emit-value
        map-options
        hide-selected
        hide-bottom-space
        class="col-7"
        input-debounce="0"
        option-label="label"
        option-value="value"
        v-model="checkup.insuranceCompany"
        :dense="dense"
        :readonly="readonly || checkup.statusSave"
        :hide-dropdown-icon="readonly || checkup.statusSave"
        :options="insuranceCompanyOptions"
        :for="`${prefixId}-select-province`"
        :label="$t('customerEmployee.formHealthCheck.insuranceCompany')"
        @filter="insuranceCompanyFilter"
      >
        <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>
</template>

<style scoped></style>
