import { useQuery } from "@tanstack/react-query";
import { useLocation } from "react-router-dom";
import { sprintf } from "sprintf-js";
import { useTranslation } from "react-i18next";
import { useWant } from "taehui-ts/fe-utility";

import { wwwAXIOS } from "src/Www";
import { AvatarAPIWantAvatar, GetAvatarAPI } from "src/wwwAPI";
import { formatText, toDate } from "src/Utility";

export type GetAvatar = {
  avatarID: string;
  avatarName: string;
  avatarIntro: string;
  totalCount: string;
  totalLength: string;
  highestCount: string;
  date: string;
  avatarLevels: number[];
  avatarAbility5KText: string;
  avatarAbility5KClass: number;
  avatarAbility5KPlace: number;
  avatarAbility5KPlaceText: string;
  avatarAbility5KCountText: string;
  avatarAbility7KText: string;
  avatarAbility7KClass: number;
  avatarAbility7KPlace: number;
  avatarAbility7KPlaceText: string;
  avatarAbility7KCountText: string;
  avatarAbility9KText: string;
  avatarAbility9KClass: number;
  avatarAbility9KPlace: number;
  avatarAbility9KPlaceText: string;
  avatarAbility9KCountText: string;
  dateSet: number[];
  dateValues: number[];
  quitStatusValues: number[];
};

export default function useGetAvatar() {
  const { want } = useWant("/qwilight/avatar");

  const { t } = useTranslation();

  const { pathname } = useLocation();

  return useQuery<AvatarAPIWantAvatar[] | GetAvatar>({
    enabled: !!want && pathname.startsWith("/qwilight/avatar"),
    queryKey: ["avatar", want],
    queryFn: async () => {
      const { data } = await wwwAXIOS.get<GetAvatarAPI>("/avatar", {
        params: want.startsWith("#")
          ? {
              avatarID: want.substring(want.indexOf("#") + 1),
            }
          : {
              avatarName: want,
            },
      });

      if (Array.isArray(data)) {
        return data;
      } else {
        return {
          ...data,
          totalCount: formatText(data.totalCount),
          totalLength: sprintf(
            t("totalLengthText"),
            Math.floor(data.totalLength / 1000 / 60 / 60),
            Math.floor((data.totalLength / 1000 / 60) % 60),
            Math.floor((data.totalLength / 1000) % 60),
          ),
          highestCount: formatText(data.highestCount),
          date: toDate(data.date),
          avatarAbility5KText: formatText(data.avatarAbility5K),
          avatarAbility5KPlaceText: formatText(data.avatarAbility5KPlace),
          avatarAbility5KCountText: formatText(data.avatarAbility5KCount),
          avatarAbility7KText: formatText(data.avatarAbility7K),
          avatarAbility7KPlaceText: formatText(data.avatarAbility7KPlace),
          avatarAbility7KCountText: formatText(data.avatarAbility7KCount),
          avatarAbility9KText: formatText(data.avatarAbility9K),
          avatarAbility9KPlaceText: formatText(data.avatarAbility9KPlace),
          avatarAbility9KCountText: formatText(data.avatarAbility9KCount),
        };
      }
    },
    initialData: [],
  });
}
