<template>
  <div>
    <div class="row items-center justify-between q-mb-md q-mt-xl">
      <div>
        <div class="text-subtitle1 text-weight-bold text-grey-8">
          {{ $t("access_log.title") }}
        </div>
        <div class="text-caption text-grey-6">
          {{ $t("access_log.description") }}
        </div>
      </div>
    </div>

    <div class="row q-col-gutter-sm q-mb-md items-end">
      <div class="col-12 col-sm-3">
        <q-select
          v-model="filters.type"
          :options="typeOptions"
          :label="$t('access_log.filter_type')"
          emit-value
          map-options
          outlined
          dense
          clearable
          color="violet-normal"
          @update:model-value="onFilterChange"
        />
      </div>

      <div class="col-12 col-sm-3">
        <q-input
          v-model="filters.date_from"
          :label="$t('access_log.filter_date_from')"
          outlined
          dense
          clearable
          color="violet-normal"
          readonly
          @clear="onFilterChange"
        >
          <template #append>
            <q-icon name="mdi-calendar" class="cursor-pointer">
              <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                <q-date
                  v-model="filters.date_from"
                  mask="YYYY-MM-DD"
                  color="violet-normal"
                  @update:model-value="onFilterChange"
                >
                  <div class="row items-center justify-end">
                    <q-btn v-close-popup flat :label="$t('common.actions.cancel')" color="grey-7" />
                    <q-btn v-close-popup flat :label="$t('common.actions.save')" color="violet-normal" />
                  </div>
                </q-date>
              </q-popup-proxy>
            </q-icon>
          </template>
        </q-input>
      </div>

      <div class="col-12 col-sm-3">
        <q-input
          v-model="filters.date_to"
          :label="$t('access_log.filter_date_to')"
          outlined
          dense
          clearable
          color="violet-normal"
          readonly
          @clear="onFilterChange"
        >
          <template #append>
            <q-icon name="mdi-calendar" class="cursor-pointer">
              <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                <q-date
                  v-model="filters.date_to"
                  mask="YYYY-MM-DD"
                  color="violet-normal"
                  :options="limitDateTo"
                  @update:model-value="onFilterChange"
                >
                  <div class="row items-center justify-end">
                    <q-btn v-close-popup flat :label="$t('common.actions.cancel')" color="grey-7" />
                    <q-btn v-close-popup flat :label="$t('common.actions.save')" color="violet-normal" />
                  </div>
                </q-date>
              </q-popup-proxy>
            </q-icon>
          </template>
        </q-input>
      </div>

      <div class="col-12 col-sm-3">
        <q-btn
          v-if="hasActiveFilters"
          flat
          dense
          no-caps
          color="violet-normal"
          icon="mdi-filter-remove-outline"
          :label="$t('access_log.clear_filters')"
          @click="clearFilters"
        />
      </div>
    </div>

    <DefaultTableServerSide
      ref="tableRef"
      :columns="columns"
      :api-call="apiCallWithFilters"
      :add-item="false"
      :show-search-field="false"
    >
      <template #body-cell-user_type="{ row }">
        <q-td class="text-center">
          <q-badge
            outline
            :color="row.user_type === 'associado' ? 'violet-normal' : 'teal'"
            :label="row.user_type === 'associado' ? $t('auth.type.associado') : $t('auth.type.parceiro')"
          />
        </q-td>
      </template>

      <template #body-cell-accessed_at="{ row }">
        <q-td>
          {{ formatDateTime(row.accessed_at) }}
        </q-td>
      </template>
    </DefaultTableServerSide>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { getAccessLogsPaginated } from "src/api/userAccessLog";
import DefaultTableServerSide from "src/components/defaults/DefaultTableServerSide.vue";

const { t } = useI18n();
const tableRef = ref(null);

const filters = ref({
  type: null,
  date_from: null,
  date_to: null,
});

const hasActiveFilters = computed(
  () => !!filters.value.type || !!filters.value.date_from || !!filters.value.date_to,
);

const typeOptions = computed(() => [
  { label: t("auth.type.associado"), value: "associado" },
  { label: t("auth.type.parceiro"),  value: "parceiro" },
]);

const columns = computed(() => [
  {
    name: "user_name",
    label: t("access_log.user"),
    field: "user_name",
    align: "left",
    sortable: false,
  },
  {
    name: "user_type",
    label: t("access_log.user_type"),
    field: "user_type",
    align: "center",
    sortable: false,
  },
  {
    name: "accessed_at",
    label: t("access_log.accessed_at"),
    field: "accessed_at",
    align: "left",
    sortable: false,
  },
]);

const apiCallWithFilters = (params) =>
  getAccessLogsPaginated({
    ...params,
    type: filters.value.type || undefined,
    date_from: filters.value.date_from || undefined,
    date_to: filters.value.date_to || undefined,
    last_per_user: true,
  });

const onFilterChange = () => {
  tableRef.value?.refresh();
};

const clearFilters = () => {
  filters.value.type = null;
  filters.value.date_from = null;
  filters.value.date_to = null;
  tableRef.value?.refresh();
};

// Data final não pode ser anterior à data inicial
const limitDateTo = (date) => {
  if (!filters.value.date_from) return true;
  return date >= filters.value.date_from.replace(/-/g, "/");
};

const formatDateTime = (isoString) => {
  if (!isoString) return "—";
  const d = new Date(isoString);
  return d.toLocaleString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};
</script>
