import { useLocale, useProgramId, useQuery, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { gql } from "graphql-request";
import { useMemo } from "@saasquatch/universal-hooks";
const GET_LEADERBOARD = gql `
  query (
    $type: String!
    $filter: UserLeaderboardFilterInput
    $locale: RSLocale
    $limit: Int!
  ) {
    userLeaderboard(type: $type, filter: $filter) {
      dateModified
      rows(limit: $limit) {
        textValue(locale: $locale)
        firstName
        lastInitial
        rank {
          rank
          denseRank
          rowNumber
        }
      }
    }
  }
`;
const GET_LEADERBOARD_WITHOUT_NAMES = gql `
  query (
    $type: String!
    $filter: UserLeaderboardFilterInput
    $locale: RSLocale
    $limit: Int!
  ) {
    userLeaderboard(type: $type, filter: $filter) {
      dateModified
      rows(limit: $limit) {
        textValue(locale: $locale)
        rank {
          rank
          denseRank
          rowNumber
        }
      }
    }
  }
`;
const GET_RANK = gql `
  query (
    $type: String!
    $filter: UserLeaderboardFilterInput
    $locale: RSLocale
  ) {
    viewer {
      ... on User {
        firstName
        lastInitial
        leaderboardRank(type: $type, filter: $filter) {
          textValue(locale: $locale)
          rank
          denseRank
          rowNumber
        }
      }
    }
  }
`;
const GET_RANK_WITHOUT_NAMES = gql `
  query (
    $type: String!
    $filter: UserLeaderboardFilterInput
    $locale: RSLocale
  ) {
    viewer {
      ... on User {
        leaderboardRank(type: $type, filter: $filter) {
          textValue(locale: $locale)
          rank
          denseRank
          rowNumber
        }
      }
    }
  }
`;
export function useLeaderboard(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
  const programIdContext = useProgramId();
  // Default to context, overriden by props
  const programId = (_a = props.programId) !== null && _a !== void 0 ? _a : programIdContext;
  const user = useUserIdentity();
  const locale = useLocale();
  const variables = programId
    ? {
      type: props.leaderboardType,
      filter: { programId_eq: programId },
    }
    : {
      type: props.leaderboardType,
      filter: {},
    };
  if (props.interval) {
    variables.filter["interval"] = props.interval;
  }
  if (locale) {
    variables["locale"] = locale;
  }
  if (props.maxRows > 0) {
    variables["limit"] = props.maxRows;
  }
  const { data: leaderboardData, loading: loadingLeaderboard, errors: leaderboardErrors, } = useQuery(props.hideNames ? GET_LEADERBOARD_WITHOUT_NAMES : GET_LEADERBOARD, variables, !(user === null || user === void 0 ? void 0 : user.jwt), { batch: false });
  const { data: rankData } = useQuery(props.hideNames ? GET_RANK_WITHOUT_NAMES : GET_RANK, variables, !(user === null || user === void 0 ? void 0 : user.jwt));
  const leaderboardRows = (_b = leaderboardData === null || leaderboardData === void 0 ? void 0 : leaderboardData.userLeaderboard) === null || _b === void 0 ? void 0 : _b.rows;
  const flattenedLeaderboard = getFlattenedLeaderboard(leaderboardRows);
  const sortedLeaderboard = flattenedLeaderboard === null || flattenedLeaderboard === void 0 ? void 0 : flattenedLeaderboard.sort(function (a, b) {
    return a.rank - b.rank;
  });
  function getFlattenedLeaderboard(leaderboardRows) {
    return leaderboardRows === null || leaderboardRows === void 0 ? void 0 : leaderboardRows.flatMap((user) => {
      var _a, _b;
      return ({
        textValue: user.textValue,
        firstName: user.firstName,
        lastInitial: user.lastInitial,
        rank: (_a = user.rank) === null || _a === void 0 ? void 0 : _a[props.rankType],
        rowNumber: (_b = user.rank) === null || _b === void 0 ? void 0 : _b.rowNumber,
      });
    });
  }
  const viewingUser = {
    textValue: (_d = (_c = rankData === null || rankData === void 0 ? void 0 : rankData.viewer) === null || _c === void 0 ? void 0 : _c.leaderboardRank) === null || _d === void 0 ? void 0 : _d.textValue,
    firstName: (_e = rankData === null || rankData === void 0 ? void 0 : rankData.viewer) === null || _e === void 0 ? void 0 : _e.firstName,
    lastInitial: (_f = rankData === null || rankData === void 0 ? void 0 : rankData.viewer) === null || _f === void 0 ? void 0 : _f.lastInitial,
    rank: (_h = (_g = rankData === null || rankData === void 0 ? void 0 : rankData.viewer) === null || _g === void 0 ? void 0 : _g.leaderboardRank) === null || _h === void 0 ? void 0 : _h[props.rankType],
    rowNumber: (_k = (_j = rankData === null || rankData === void 0 ? void 0 : rankData.viewer) === null || _j === void 0 ? void 0 : _j.leaderboardRank) === null || _k === void 0 ? void 0 : _k.rowNumber,
  };
  // Show feature enforcement if request was forbidden
  const isEssentials = useMemo(() => {
    var _a, _b;
    return !!((_b = (_a = leaderboardErrors === null || leaderboardErrors === void 0 ? void 0 : leaderboardErrors.response) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b.find((error) => { var _a, _b; return ((_b = (_a = error === null || error === void 0 ? void 0 : error.extensions) === null || _a === void 0 ? void 0 : _a.apiError) === null || _b === void 0 ? void 0 : _b.statusCode) === 403; }));
  }, [leaderboardErrors]);
  return {
    states: {
      loading: loadingLeaderboard,
      isEssentials,
      hasLeaders: (sortedLeaderboard === null || sortedLeaderboard === void 0 ? void 0 : sortedLeaderboard.length) > 0,
      styles: props,
    },
    data: {
      leaderboard: sortedLeaderboard,
      rankType: props.rankType,
      viewerRank: viewingUser,
    },
    elements: {
      empty: props.empty,
    },
  };
}
