<script setup lang="ts">
import { calculateAge, dateFormat } from 'src/utils/datetime';
import { baseUrl } from 'src/stores/utils';

import PersonCard from 'components/shared/PersonCard.vue';
import KebabAction from '../shared/KebabAction.vue';
import useOptionStore from 'stores/options';

const optionStore = useOptionStore();
const pageSize = defineModel<number>('pageSize', { default: 30 });
const currentPage = defineModel<number>('currentPage', { default: 1 });

const prop = withDefaults(
  defineProps<{
    gridView?: boolean;
    listEmployee: any[];
    columnsEmployee: any[];
    fieldSelected?: string[];
    inTable?: boolean;
  }>(),
  {
    gridView: false,
    fieldSelected: () => [
      'orderNumber',
      'firstName',
      'general.age',
      'formDialogInputNationality',
      'formDialogInputPassportNo',
      'passportExpiryDate',
      'formDialogEmployeeNRCNo',
      'branchLabel',
      'action',
    ],
  },
);

defineEmits<{
  (e: 'view', data: any): void;
  (e: 'edit', data: any): void;
  (e: 'delete', data: any): void;
  (e: 'toggleStatus', data: any): void;
}>();
</script>

<template>
  <q-table
    flat
    bordered
    :grid="gridView"
    :rows="listEmployee"
    :columns="columnsEmployee"
    class="full-width"
    card-container-class="q-col-gutter-md"
    row-key="name"
    :rows-per-page-options="[0]"
    hide-pagination
    :visible-columns="fieldSelected"
  >
    <template v-slot:header="props">
      <q-tr
        :style="`background-color:   ${inTable ? '#F0FFF1' : 'hsla(var(--info-bg) / 0.07'} `"
        :props="props"
      >
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span v-if="col.label === 'nameEmployee'">
            {{ $t('fullname') }}
          </span>

          <span v-if="col.label !== ''">
            {{ $t(col.label) }}
          </span>
        </q-th>
      </q-tr>
    </template>

    <template v-slot:body="props">
      <q-tr
        :style="
          props.rowIndex % 2 !== 0
            ? $q.dark.isActive
              ? 'background: hsl(var(--gray-11-hsl)/0.2)'
              : `background: #f9fafc`
            : ''
        "
        :class="{
          'app-text-muted': props.row.status === 'INACTIVE',
          'status-active': props.row.status !== 'INACTIVE',
          'status-inactive': props.row.status === 'INACTIVE',
        }"
        :props="props"
        :id="`row-table-${props.row.firstNameEN}`"
        @click="
          () => {
            // employeeFormState.drawerModal = true;
            // employeeFormStore.assignFormDataEmployee(
            //   props.row.id,
            // );
            // $router.push(`/customer-management/${props.row.id}/branch`);
            // openDialogInputForm('INFO', props.row.id);
          }
        "
      >
        <q-td class="text-center" v-if="fieldSelected.includes('orderNumber')">
          {{ (currentPage - 1) * pageSize + props.rowIndex + 1 }}
        </q-td>

        <q-td v-if="fieldSelected.includes('firstName')">
          <div class="row items-center" style="flex-wrap: nowrap">
            <div
              style="width: 50px; display: flex; margin-bottom: var(--size-2)"
            >
              <div
                style="
                  border-radius: 50%;
                  border-style: solid;
                  border-width: 2px;
                  border-color: hsl(var(--pink-6-hsl));
                  padding: 3px;
                "
              >
                <div class="full-width full-height">
                  <q-avatar size="md">
                    <q-img
                      :src="
                        `${baseUrl}/employee/${props.row.id}/image/${props.row.selectedImage}` ||
                        '/images/employee-avatar.png'
                      "
                      class="text-center"
                      :ratio="1"
                    >
                      <template #error>
                        <span>
                          <q-img
                            class="text-center"
                            :ratio="1"
                            src="/images/employee-avatar.png"
                          />
                        </span>
                      </template>
                    </q-img>

                    <q-badge
                      class="absolute-bottom-right no-padding"
                      style="
                        border-radius: 50%;
                        min-width: 8px;
                        min-height: 8px;
                      "
                      :style="{
                        background: `var(--${props.row.status === 'INACTIVE' ? 'stone-5' : 'green-6'})`,
                      }"
                    ></q-badge>
                  </q-avatar>
                </div>
              </div>
            </div>

            <div class="col text-left">
              <div class="col">
                {{ `${props.row.firstName} ${props.row.lastName}` || '-' }}

                <q-icon
                  class="q-pl-xs"
                  :class="{
                    'symbol-gender': props.row.gender,
                    'symbol-gender__male': props.row.gender === 'male',
                    'symbol-gender__female': props.row.gender === 'female',
                  }"
                  :name="`mdi-gender-${props.row.gender === 'male' ? 'male' : 'female'}`"
                  width="24px"
                />
              </div>
              <div class="col app-text-muted">
                {{ `${props.row.firstNameEN} ${props.row.lastNameEN}` || '-' }}
              </div>
            </div>
          </div>
        </q-td>

        <q-td v-if="fieldSelected.includes('general.age')">
          {{ calculateAge(props.row.dateOfBirth) || '-' }}
        </q-td>

        <q-td v-if="fieldSelected.includes('formDialogInputNationality')">
          {{ optionStore.mapOption(props.row.nationality || '-') }}
        </q-td>

        <q-td v-if="fieldSelected.includes('formDialogInputPassportNo')">
          {{ props.row.passportNumber || '-' }}
        </q-td>

        <q-td v-if="fieldSelected.includes('passportExpiryDate')">
          {{ dateFormat(props.row.passportExpiryDate) || '-' }}
        </q-td>

        <q-td v-if="fieldSelected.includes('formDialogEmployeeNRCNo')">
          {{ props.row.nrcNo || '-' }}
        </q-td>

        <q-td v-if="fieldSelected.includes('branchLabel')">
          <div class="row items-center" v-if="props.row.customerBranch">
            <div class="col text-left">
              <div class="col">
                {{ props.row.customerBranch.code || '-' }}
              </div>
              <div class="col app-text-muted">
                {{
                  $i18n.locale === 'eng'
                    ? `${props.row.customerBranch.registerNameEN}`
                    : `${props.row.customerBranch.registerName}`
                }}
              </div>
            </div>
          </div>
        </q-td>

        <q-td>
          <q-btn
            icon="mdi-eye-outline"
            size="sm"
            dense
            round
            flat
            @click.stop="$emit('view', props.row)"
          />

          <KebabAction
            :id-name="props.row.code"
            :status="props.row.status"
            @view="$emit('view', props.row)"
            @edit="$emit('edit', props.row)"
            @delete="$emit('delete', props.row)"
            @change-status="$emit('toggleStatus', props.row)"
          />
        </q-td>
      </q-tr>
    </template>

    <template v-slot:item="props">
      <div class="col-12 col-md-3 col-sm-6">
        <PersonCard
          :id="`card-${props.row.firstNameEN}`"
          :field-selected="fieldSelected"
          history
          :prefix-id="props.row.firstNameEN ?? props.rowIndex"
          :data="{
            code: props.row.code,
            name:
              $i18n.locale === 'eng'
                ? `${props.row.firstNameEN} ${props.row.lastNameEN} `.trim()
                : `${props.row.firstName} ${props.row.lastName} `.trim(),
            img:
              `${baseUrl}/employee/${props.row.id}/image/${props.row.selectedImage}` ||
              '/images/employee-avatar.png',
            fallbackImg: '/images/employee-avatar.png',
            male: props.row.gender === 'male',
            female: props.row.gender === 'female',
            detail: [
              {
                icon: 'mdi-passport',
                value: props.row.nationality,
              },

              {
                icon: 'mdi-clock-outline',
                value: props.row.dateOfBirth
                  ? (calculateAge(props.row.dateOfBirth) ?? '')
                  : '',
              },
            ],
          }"
          :tag="[
            {
              color: 'pink',
              value: $t('customer.employee'),
            },
          ]"
          :disabled="props.row.status === 'INACTIVE'"
          @history="() => $emit('history', props.row)"
          @update-card="() => $emit('edit', props.row)"
          @enter-card="() => $emit('view', props.row)"
          @delete-card="() => $emit('delete', props.row)"
          @toggle-status="() => $emit('toggleStatus', props.row)"
        />
      </div>
    </template>
  </q-table>
</template>

<style scoped>
.branch-card__icon {
  background-color: hsla(var(--_branch-card-bg) / 0.15);
  border-radius: 50%;
  padding: var(--size-1);
  position: relative;
  transform: rotate(45deg);

  &::after {
    content: ' ';
    display: block;
    block-size: 0.5rem;
    aspect-ratio: 1;
    position: absolute;
    border-radius: 50%;
    right: -0.1rem;
    top: calc(50% - 0.25rem);
    bottom: calc(50% - 0.25rem);
    background-color: hsla(var(--_branch-status-color) / 1);
  }

  & :deep(.q-avatar) {
    transform: rotate(-45deg);
    color: hsla(var(--_branch-card-bg) / 1);
  }
}

& .symbol-gender {
  color: hsla(var(--_fg));

  &.symbol-gender__male {
    --_fg: var(--gender-male);
  }

  &.symbol-gender__female {
    --_fg: var(--gender-female);
  }
}
</style>
