<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { dateFormat } from 'src/utils/datetime';
import useAddressStore, {
  District,
  Province,
  SubDistrict,
} from 'src/stores/address';
import { EmployeeCheckupCreate } from 'src/stores/employee/types';

const adrressStore = useAddressStore();

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

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

const tab = ref();

defineProps<{
  title?: string;
  dense?: boolean;
  outlined?: boolean;
  readonly?: boolean;
  separator?: boolean;
  typeCustomer?: string;
}>();

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

  if (result) addrOptions.provinceOps = result;
}

function addData() {
  employeeCheckup.value?.push({
    coverageExpireDate: null,
    coverageStartDate: null,
    insuranceCompany: '',
    medicalBenefitScheme: '',
    remark: '',
    hospitalName: '',
    provinceId: '',
    checkupResult: '',
    checkupType: '',
  });
  if (employeeCheckup.value)
    tab.value = `tab${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';
});
</script>

<template>
  <div>
    <div class="bordered-b full-width">
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-class="active-tab"
        indicator-color="transparent"
        align="left"
        :breakpoint="0"
      >
        <q-btn
          @click="addData"
          flat
          class="app-text-muted"
          style="background-color: var(--_body-bg)"
          icon="mdi-plus"
          padding="8px 8px"
          :disable="readonly"
          :color="$q.dark.isActive ? 'primary' : ''"
          :class="tab !== 'tab0' ? 'bordered-r' : ''"
        />
        <q-tab
          v-for="(tab, index) in employeeCheckup"
          v-bind:key="index"
          :name="`tab${index}`"
          class="content-tab text-capitalize"
          style="z-index: 999"
        >
          <div class="text-weight-medium row items-center">
            {{ $t('formDialogTabCheckup') + (index + 1) }}
            <q-btn
              v-if="!readonly && employeeCheckup?.length !== 1"
              round
              flat
              id="closeDialog"
              size="sm"
              icon="mdi-close"
              padding="xs"
              color="red"
              :class="{ dark: $q.dark.isActive }"
              @click.stop="removeData(index)"
            />
          </div>
        </q-tab>
      </q-tabs>
    </div>

    <q-tab-panels v-model="tab" style="padding-top: 0px">
      <q-tab-panel
        v-for="(checkup, index) in employeeCheckup"
        v-bind:key="index"
        :name="`tab${index}`"
        class="row col-12 items-start"
        style="overflow: auto"
      >
        <div class="col-3 app-text-muted">
          • {{ $t(`formDialogTitleHealthCheck`) }}
        </div>
        <div class="col-9 row q-col-gutter-md">
          <q-input
            :dense="dense"
            :outlined="!readonly"
            :readonly="readonly"
            :borderless="readonly"
            hide-bottom-space
            class="col-6"
            :label="$t('formDialogInputCheckupRes')"
            v-model="checkup.checkupResult"
          />
          <q-select
            id="select-province"
            :dense="dense"
            :readonly="readonly"
            :outlined="readonly ? false : outlined"
            :hide-dropdown-icon="readonly"
            :borderless="readonly"
            hide-bottom-space
            emit-value
            map-options
            v-model="checkup.checkupType"
            option-value="value"
            option-label="label"
            :label="$t('formDialogInputCheckupType')"
            class="col-6"
            :options="checkupTypeOption"
            lazy-rules
          />
          <q-select
            id="select-province"
            :dense="dense"
            :readonly="readonly"
            :outlined="readonly ? false : outlined"
            :hide-dropdown-icon="readonly"
            :borderless="readonly"
            hide-bottom-space
            emit-value
            map-options
            v-model="checkup.provinceId"
            option-value="id"
            option-label="name"
            :label="$t('province')"
            class="col-3"
            :options="addrOptions.provinceOps"
            lazy-rules
          />
          <q-input
            :dense="dense"
            :outlined="!readonly"
            :readonly="readonly"
            :borderless="readonly"
            hide-bottom-space
            class="col-9"
            :label="$t('formDialogInputHospital')"
            v-model="checkup.hospitalName"
          />
          <q-input
            :label="$t('formDialogInputRemark')"
            :dense="dense"
            :outlined="!readonly"
            :readonly="readonly"
            :borderless="readonly"
            hide-bottom-space
            class="col-12"
            v-model="checkup.remark"
            type="textarea"
          />
          <q-select
            id="select-province"
            :dense="dense"
            :readonly="readonly"
            :outlined="readonly ? false : outlined"
            :hide-dropdown-icon="readonly"
            :borderless="readonly"
            hide-bottom-space
            emit-value
            map-options
            v-model="checkup.medicalBenefitScheme"
            option-value="value"
            option-label="label"
            :label="$t('formDialogInputMedicalBenefit')"
            class="col-6"
            :options="medicalBenefitOption"
            lazy-rules
          />
          <q-select
            id="select-province"
            :dense="dense"
            :readonly="readonly"
            :outlined="readonly ? false : outlined"
            :hide-dropdown-icon="readonly"
            :borderless="readonly"
            hide-bottom-space
            emit-value
            map-options
            v-model="checkup.insuranceCompany"
            option-value="value"
            option-label="label"
            :label="$t('formDialogInputInsuranceCompany')"
            class="col-6"
            :options="insuranceCompanyOption"
            lazy-rules
          />
          <VueDatePicker
            utc
            autoApply
            :teleport="true"
            v-model="checkup.coverageStartDate"
            :locale="'th'"
            :enableTimePicker="false"
            :disabled="readonly"
            class="col-3"
          >
            <template #year="{ value }">
              {{ value + 543 }}
            </template>
            <template #trigger>
              <q-input
                id="input-birth-date"
                :label="$t('formDialogInputCoverageStartDate')"
                :dense="dense"
                :outlined="readonly ? false : outlined"
                :readonly="readonly"
                :borderless="readonly"
                :model-value="
                  checkup.coverageStartDate
                    ? dateFormat(checkup.coverageStartDate)
                    : ''
                "
              >
                <template v-slot:prepend>
                  <q-icon
                    size="xs"
                    name="mdi-calendar-blank-outline"
                    class="cursor-pointer"
                    color="positive"
                  />
                </template>
                <template v-slot:append>
                  <q-icon
                    v-if="checkup.coverageStartDate && !readonly"
                    name="mdi-close"
                    class="cursor-pointer"
                    size="xs"
                    @click="checkup.coverageStartDate = undefined"
                  />
                </template>
              </q-input>
            </template>
          </VueDatePicker>
          <VueDatePicker
            utc
            autoApply
            :teleport="true"
            v-model="checkup.coverageExpireDate"
            :locale="'th'"
            :enableTimePicker="false"
            :disabled="readonly"
            class="col-3"
          >
            <template #year="{ value }">
              {{ value + 543 }}
            </template>
            <template #trigger>
              <q-input
                id="input-birth-date"
                :label="$t('formDialogInputCoverageExpiretDate')"
                :dense="dense"
                :outlined="readonly ? false : outlined"
                :readonly="readonly"
                :borderless="readonly"
                :model-value="
                  checkup.coverageExpireDate
                    ? dateFormat(checkup.coverageExpireDate)
                    : ''
                "
              >
                <template v-slot:prepend>
                  <q-icon
                    size="xs"
                    name="mdi-calendar-blank-outline"
                    class="cursor-pointer"
                    color="positive"
                  />
                </template>
                <template v-slot:append>
                  <q-icon
                    v-if="checkup.coverageExpireDate && !readonly"
                    name="mdi-close"
                    class="cursor-pointer"
                    size="xs"
                    @click="checkup.coverageExpireDate = undefined"
                  />
                </template>
              </q-input>
            </template>
          </VueDatePicker>
        </div>

        <q-separator
          v-if="separator"
          class="col-12 q-mt-xl q-mb-md"
          style="padding-block: 0.5px"
        />
      </q-tab-panel>
    </q-tab-panels>
  </div>
</template>

<style scoped>
.active-tab {
  color: var(--brand-1);
  border-left: 1px solid var(--border-color);
  border-right: 1px solid var(--border-color);
  margin-bottom: -1.5px;
  border-bottom: 3px solid var(--surface-1);
}
</style>
