<template>
  <div>
    <input
      ref="importFileInput"
      type="file"
      accept=".xlsx"
      class="hidden"
      @change="onFileSelected"
    />

    <DefaultHeaderPage>
      <template #after>
        <div class="flex gap-sm q-mt-md">
          <q-btn
            unelevated
            dense
            no-caps
            class="btn-gradient"
            :label="$t('associado.import_afastamentos')"
            icon="mdi-upload"
            padding="6px 10px"
          />
          <q-btn
            unelevated
            dense
            no-caps
            class="btn-gradient"
            :label="$t('associado.import_associados')"
            icon="mdi-upload"
            padding="6px 10px"
            :loading="importing"
            @click="onImportClick"
          />
          <q-btn
            unelevated
            dense
            class="btn-gradient"
            icon="mdi-clock-outline"
            padding="6px 10px"
            :title="$t('import_log.history_title')"
            @click="onOpenImportHistory"
          />
          <q-btn
            unelevated
            dense
            class="btn-gradient"
            icon="mdi-plus"
            padding="6px 10px"
            @click="onAddItem"
          />
        </div>
      </template>
    </DefaultHeaderPage>

    <DefaultTableServerSide
      ref="tableRef"
      :columns="columns"
      :api-call="getAssociadosPaginated"
      :add-item="false"
      :extra-filters="extraFilters"
      align-actions-left
      open-item
      @on-row-click="onRowClick"
    >
      <template #filters>
        <PositionSelect
          v-model="selectedPosition"
          clearable
          dense
          outlined
          color="violet-normal"
          class="col-xs-12 col-sm-6 col-md-auto"
          style="min-width: 180px"
          :placeholder="$t('associado.filter_by_position')"
        />
        <SectorSelect
          v-model="selectedSector"
          clearable
          dense
          outlined
          color="violet-normal"
          class="col-xs-12 col-sm-6 col-md-auto"
          style="min-width: 180px"
          :placeholder="$t('associado.filter_by_sector')"
        />
      </template>

      <template #body-cell-actions="{ row }">
        <div class="row no-wrap justify-start items-center" style="gap: 4px">
          <q-btn flat round dense color="violet-normal" icon="mdi-pencil" @click.stop="onRowClick({ row })" />
          <q-btn
            flat round dense
            :color="row.status === 'on_leave' || row.status?.value === 'on_leave' ? 'grey-4' : 'violet-normal'"
            icon="mdi-account-minus"
            :disable="row.status === 'on_leave' || row.status?.value === 'on_leave'"
            @click.stop="onSetOnLeave(row)"
          />
          <q-btn flat round dense color="violet-normal" icon="mdi-calendar" @click.stop="onOpenAppointments(row)" />
          <q-btn
            v-if="row.status === 'pending' || row.status?.value === 'pending'"
            flat 
            round 
            dense 
            color="violet-normal"
            icon="mdi-check-circle-outline"
            :title="$t('associado.approve_confirm')"
            @click.stop="onApprove(row)"
          />
        </div>
      </template>

      <template #body-cell-status="{ row }">
        <q-td class="text-center">
          <q-badge
            outline
            :color="getStatusColor(row.status)"
            :label="$t(getStatusI18nKey(row.status))"
          />
        </q-td>
      </template>

      <template #body-cell-first_access_at="{ row }">
        <q-td class="text-center">
          <q-badge
            outline
            :color="row.first_access_at ? 'positive' : 'grey-6'"
            :label="row.first_access_at ? $t('common.status.yes') : $t('common.status.no')"
          >
            <q-tooltip v-if="row.first_access_at">{{ row.first_access_at }}</q-tooltip>
          </q-badge>
        </q-td>
      </template>
    </DefaultTableServerSide>

    <q-separator class="q-my-xl" />

    <AccessLogsTable />
  </div>
</template>

<script setup>
import { ref, computed, defineAsyncComponent, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { permissionStore } from "src/stores/permission";
import { getAssociadosPaginated, importAssociados, setUserOnLeave, approveUser } from "src/api/user";
import { getStatusColor, getStatusI18nKey } from "src/helpers/utils";
import { useImportPoller } from "src/composables/useImportPoller";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTableServerSide from "src/components/defaults/DefaultTableServerSide.vue";
import PositionSelect from "src/components/selects/PositionSelect.vue";
import SectorSelect from "src/components/selects/SectorSelect.vue";
import AccessLogsTable from "./components/AccessLogsTable.vue";

const AddEditAssociadoDialog = defineAsyncComponent(
  () => import("./components/AddEditAssociadoDialog.vue"),
);
const ImportHistoryDialog = defineAsyncComponent(
  () => import("src/components/ImportHistoryDialog.vue"),
);
const AssociadoAppointmentsDialog = defineAsyncComponent(
  () => import("./components/AssociadoAppointmentsDialog.vue"),
);

const permission_store = permissionStore();
const $q = useQuasar();
const { t } = useI18n();
const tableRef = ref(null);
const importFileInput = useTemplateRef("importFileInput");
const { polling: importing, start: startPolling } = useImportPoller();

const selectedPosition = ref(null);
const selectedSector = ref(null);
const extraFilters = computed(() => ({
  position_id: selectedPosition.value?.value,
  sector_id: selectedSector.value?.value,
}));

const columns = computed(() => [
  {
    name: "registration",
    label: t("associado.cracha"),
    field: "registration",
    align: "left",
    sortable: true,
    width: "10%",
  },
  {
    name: "name",
    label: t("common.terms.name"),
    field: "name",
    align: "left",
    sortable: true,
    width: "25%",
  },
  {
    name: "position",
    label: t("associado.position"),
    field: (row) => row.position?.name ?? "—",
    align: "left",
    sortable: true,
    width: "25%",
  },
  {
    name: "admission_date",
    label: t("associado.admission"),
    field: (row) => (row.admission_date ? row.admission_date : "—"),
    align: "left",
    sortable: true,
    width: "10%",
  },
  {
    name: "expiry_date",
    label: t("associado.validity"),
    field: (row) => (row.expiry_date ? row.expiry_date : "—"),
    align: "left",
    sortable: true,
    width: "10%",
  },
  {
    name: "first_access_at",
    label: t("associado.primeiro_acesso"),
    field: "first_access_at",
    align: "center",
    width: "10%",
  },
  {
    name: "actions",
    label: t("common.terms.actions"),
    align: "center",
    required: true,
    width: "15%",
  },
  {
    name: "status",
    label: t("common.terms.status"),
    field: "status",
    align: "center",
    sortable: true,
    width: "5%",
  },
]);

const onAddItem = async () => {
  if (!permission_store.getAccess("associado", "add")) {
    $q.notify({ type: "negative", message: t("validation.permissions.add") });
    return;
  }
  $q.dialog({ component: AddEditAssociadoDialog }).onOk(() => {
    tableRef.value?.refresh();
  });
};

const onRowClick = async ({ row }) => {
  if (!permission_store.getAccess("associado", "edit")) {
    $q.notify({ type: "negative", message: t("validation.permissions.edit") });
    return;
  }
  $q.dialog({
    component: AddEditAssociadoDialog,
    componentProps: {
      associado: row,
      title: () => t("common.actions.edit") + " " + t("ui.navigation.associados"),
    },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
};

const onSetOnLeave = (row) => {
  if (!permission_store.getAccess("associado", "edit")) {
    $q.notify({ type: "negative", message: t("validation.permissions.edit") });
    return;
  }

  $q.dialog({
    title: t("associado.set_on_leave_title"),
    message: t("associado.set_on_leave_message", { name: row.name }),
    cancel: { flat: true, label: t("common.actions.cancel"), color: "grey-7" },
    ok: { unelevated: true, label: t("associado.set_on_leave_confirm"), color: "violet-normal" },
    persistent: true,
  }).onOk(async () => {
    try {
      await setUserOnLeave(row.id);
      tableRef.value?.refresh();
    } catch {
      // silent
    }
  });
};

const onApprove = (row) => {
  if (!permission_store.getAccess("associado", "edit")) {
    $q.notify({ type: "negative", message: t("validation.permissions.edit") });
    return;
  }

  $q.dialog({
    title: t("associado.approve_title"),
    message: t("associado.approve_message", { name: row.name }),
    cancel: { flat: true, label: t("common.actions.cancel"), color: "grey-7" },
    ok: { unelevated: true, label: t("associado.approve_confirm"), color: "violet-normal" },
    persistent: true,
  }).onOk(async () => {
    try {
      await approveUser(row.id);
      tableRef.value?.refresh();
    } catch {
      // silent
    }
  });
};

const onOpenAppointments = (row) => {
  if (!permission_store.getAccess("agendamento", "view")) {
    $q.notify({ type: "negative", message: t("validation.permissions.view") });
    return;
  }
  $q.dialog({
    component: AssociadoAppointmentsDialog,
    componentProps: { associado: row },
  });
};

const onOpenImportHistory = () => {
  $q.dialog({ component: ImportHistoryDialog, componentProps: { type: 'associado' } });
};

const onImportClick = () => {
  if (!permission_store.getAccess("associado", "add")) {
    $q.notify({ type: "negative", message: t("validation.permissions.add") });
    return;
  }
  importFileInput.value.value = null;
  importFileInput.value.click();
};

const onFileSelected = async (event) => {
  const file = event.target.files?.[0];
  if (!file) return;

  try {
    const { import_id } = await importAssociados(file);

    startPolling(import_id, {
      onComplete: (stats) => {
        $q.notify({
          type: "positive",
          message: t("associado.import_sync_result", {
            created:     stats.created,
            updated:     stats.updated,
            inactivated: stats.inactivated,
          }),
          timeout: 6000,
        });
        tableRef.value?.refresh();
      },
      onError: () => $q.notify({ type: "negative", message: t("http.errors.failed") }),
      onTimeout: () => $q.notify({ type: "warning", message: t("associado.import_processing") }),
    });
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  }
};
</script>

<style scoped>
.gap-sm {
  gap: 8px;
}

.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 8px !important;
}

.btn-gradient :deep(.q-icon) {
  color: white !important;
}
</style>
