<template>
  <q-page class="q-pa-md">
    <SettingsTabsHeader />

    <DefaultTable
      :add-item="canCreateUserType"
      :add-item-route="'SettingsUserTypeCreatePage'"
      :api-call="fetchUserTypesRows"
      :columns="columns"
      open-item
      @on-row-click="onRowClick"
    >
      <template #body-cell-permissions="{ row }">
        <q-td align="center">
          <q-chip
            v-if="row.permissionsCount"
            color="primary"
            dense
            outline
          >
            {{ row.permissionsCount }}
            <q-tooltip
              class="bg-grey-2 text-grey-9 shadow-1 permissions-tooltip"
            >
              <div
                v-for="permission in row.permissionsTooltipLines"
                :key="permission"
                class="q-mb-xs"
              >
                {{ permission }}
              </div>
            </q-tooltip>
          </q-chip>

          <span v-else>-</span>
        </q-td>
      </template>

      <template #body-cell-locked="{ row }">
        <q-td align="center">
          <q-badge
            text-color="white"
            :color="row.locked ? 'blue-grey-8' : 'green-7'"
            :label="
              row.locked
                ? $t('settings.user_types.locked')
                : $t('settings.user_types.editable')
            "
          />
        </q-td>
      </template>

      <template #body-cell-actions>
        <q-td align="center">
          <q-icon name="mdi-playlist-edit" size="md" />
        </q-td>
      </template>
    </DefaultTable>
  </q-page>
</template>

<script setup>
import {
  buildPermissionTooltipLines,
  isLockedUserTypePermission,
  normalizeUserTypeOptions,
  translateUserTypeLabelUppercase
} from "./utils";

import { computed, ref } from "vue";
import { getPermissionCatalog, getPermissionsByUserType } from "src/api/permission";
import { permissionStore } from "src/stores/permission";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { userTypes } from "src/api/user";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
import SettingsTabsHeader from "./components/SettingsTabsHeader.vue";

const router = useRouter();

const { t } = useI18n();
const { getAccess } = permissionStore();

const canCreateUserType = computed(() =>
  getAccess("config.permission", "add"),
);

const columns = ref([
  { name: "id",    field: "id",    label: "ID",                            sortable: true, align: "left", style: "width: 80px" },
  { name: "label", field: "label", label: t("settings.user_types.single"), sortable: true, align: "left" },

  { name: "permissions", field: "permissions", label: t("settings.user_types.permissions"), align: "center" },
  { name: "locked",      field: "locked",      label: t("common.terms.status"),             align: "center" },
  { name: "actions",     field: "actions",     label: t("settings.user_types.actions"),     align: "center" },
]);

const fetchUserTypesRows = async () => {
  const [response, permissionCatalog] = await Promise.all([
    userTypes(),
    getPermissionCatalog(),
  ]);

  const options = normalizeUserTypeOptions(response, t);

  const permissionsByUserType = await Promise.all(
    options.map(async (option) => ({
      id: option.id, assignedPermissions: await getPermissionsByUserType(option.id),
    })),
  );

  const assignedPermissionsMap = new Map(
    permissionsByUserType.map((item) => [item.id, item.assignedPermissions]),
  );

  return options.map((option) => {
    const assignedPermissions = assignedPermissionsMap.get(option.id) || [];

    const permissionsTooltipLines = buildPermissionTooltipLines(
      permissionCatalog,
      assignedPermissions,
      t,
    );

    return {
      id: option.id, label: translateUserTypeLabelUppercase(option, t),

      permissionsCount: permissionsTooltipLines.length,

      permissionsTooltipLines,

      locked: isLockedUserTypePermission(option),
    };
  });
};

const onRowClick = ({ row }) => {
  router.push({
    name: "SettingsUserTypeEditPage", params: { userTypeId: row.id },
  });
};
</script>

<style scoped lang="scss">
.permissions-tooltip {
  max-width: 420px;
}
</style>
