import React, { useCallback, useState } from "react";
import { useDispatch } from "react-redux";
import { ArticleStore } from "../domain/articleStore";
import type { Article } from "../domain/articleEntity";
import { getArticle as getArticleAPI } from "./articleAPIService";

const useArticleCommonStore = (): ArticleStore => {
  const [isLoading, setLoading] = useState<boolean>(false);
  const [hasError, setError] = useState<boolean>(false);
  const [article, setArticleState] = useState<Article | undefined>();

  const dispatch = useDispatch();

  const getArticle = useCallback(
    async (id: string) => {
      setLoading(true);
      try {
        const article = await getArticleAPI(id);
        setArticleState(article);
        setLoading(false);
        return article;
      } catch (error) {
        setError(true);
        return null;
      }
    },
    [dispatch]
  );

  return {
    article: article,
    isLoading,
    hasError,
    setArticle: setArticleState,
    getArticle,
  };
};

export { useArticleCommonStore };
