import { useQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { toast } from "sonner";

import { useI18n } from "../i18n/hooks";

import { loadModels } from "./api";
import type { Model } from "./types";

const MODELS_UPDATING_TOAST_ID = "models-server-updating";

export function useModels({ enabled = true }: { enabled?: boolean } = {}) {
  const { t } = useI18n();
  const { data, isLoading, error, failureReason } = useQuery<Model[], Error>({
    queryKey: ["models"],
    queryFn: () => loadModels(),
    enabled,
    refetchOnWindowFocus: false,
    retry: (failureCount, queryError) => {
      if (queryError.message.startsWith("HTTP error: 4")) {
        return false;
      }
      if (queryError.message.startsWith("Server error: 5")) {
        return true;
      }
      return failureCount < 1;
    },
    retryDelay: 3000,
  });

  useEffect(() => {
    const serverError = [failureReason, error].find((candidate) =>
      candidate?.message.includes("Server error: 5"),
    );

    if (serverError) {
      toast.loading(t.models.updating, {
        id: MODELS_UPDATING_TOAST_ID,
      });
      return;
    }

    toast.dismiss(MODELS_UPDATING_TOAST_ID);
  }, [error, failureReason]);

  useEffect(() => {
    if (error?.message.includes("HTTP error: 4")) {
      toast.error(t.models.apiUnavailable);
    }
  }, [error, t.models.apiUnavailable]);

  return { models: data ?? [], isLoading, error };
}
