import { AvatarAPIAvatar, AvatarAPIWantAvatar } from "@/type/wwwAPI";
import { formatText } from "@/utilities/Utility";
import { wwwAPI } from "@/utilities/wwwAPI";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { useMemo } from "react";
import { getDatetime } from "taehui-lib/date";
import { useIsPath } from "taehui-lib/fe-utilities";

export type GetAvatar = {
  avatarID: string;
  avatarName: string;
  avatarIntro: string;
  totalCount: string;
  totalLength: string;
  topCount: string;
  date: string;
  avatarLevels: number[];
  avatarAbility5K: number;
  avatarAbility5KText: string;
  avatarAbility5KPlace: number;
  avatarAbility5KCount: number;
  avatarAbility7K: number;
  avatarAbility7KText: string;
  avatarAbility7KPlace: number;
  avatarAbility7KCount: number;
  avatarAbility9K: number;
  avatarAbility9KText: string;
  avatarAbility9KPlace: number;
  avatarAbility9KCount: number;
  dateSet: number[];
  dateValues: number[];
  quitStatusValues: number[];
};

export default function useGetAvatar() {
  let { want: [want] = [""] } = useParams<{ want: string[] }>();
  want = useMemo(() => decodeURIComponent(want), [want]);

  const t = useTranslations();

  const isPath = useIsPath();

  return useQuery<AvatarAPIWantAvatar[] | GetAvatar>({
    enabled: !!want && isPath("/avatar"),
    queryKey: ["avatar", want],
    queryFn: async () => {
      const { data } = await wwwAPI.get<
        AvatarAPIWantAvatar[] | AvatarAPIAvatar
      >("/avatar", {
        params: { want },
      });

      if (!data) {
        return [];
      }

      if (Array.isArray(data)) {
        return data;
      } else {
        return {
          ...data,
          totalCount: formatText(data.totalCount),
          totalLength: t("totalLengthText", {
            h: Math.floor(data.totalLength / 1000 / 60 / 60),
            m: Math.floor((data.totalLength / 1000 / 60) % 60),
            s: Math.floor((data.totalLength / 1000) % 60),
          }),
          topCount: formatText(data.topCount),
          date: getDatetime(data.date),
          avatarAbility5K: data.avatarAbility5K,
          avatarAbility5KText: formatText(data.avatarAbility5K),
          avatarAbility5KCount: data.avatarAbility5KCount,
          avatarAbility7K: data.avatarAbility7K,
          avatarAbility7KText: formatText(data.avatarAbility7K),
          avatarAbility7KCount: data.avatarAbility7KCount,
          avatarAbility9K: data.avatarAbility9K,
          avatarAbility9KText: formatText(data.avatarAbility9K),
          avatarAbility9KCount: data.avatarAbility9KCount,
        };
      }
    },
    initialData: [],
  });
}
