import {
  CommentItem,
  CommentReplyItem,
  ReplyComment,
} from "@/contexts/types/tasks";
import {
  axiosInstance,
  axiosInstance1,
  endpoints,
  fetcher1,
} from "@/utils/axios";
import axios from "axios";
import { useMemo, useState, useEffect } from "react";
import useSWR from "swr";

export const useGetComments = (taskId: number, refreshKey: number = 0) => {
  const [comments, setComments] = useState<CommentItem[]>([]);

  useEffect(() => {
    const fetchComments = async () => {
      try {
        const response = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/comments/${taskId}`
        );
        setComments(response.data);
      } catch (error) {
        console.error('Error fetching comments:', error);
      }
    };

    if (taskId) {
      fetchComments();
    }
  }, [taskId, refreshKey]); // Add refreshKey to dependencies

  return { comments };
};

export async function createComment(commentData: CommentItem) {
  const URL = endpoints.comment.list;
  return await axiosInstance1.post(URL, commentData);
}
export async function postReplyComment(commentData: CommentReplyItem) {
  const URL = endpoints.comment.reply;
  try {
    return await axiosInstance1.post(URL, commentData);
  } catch (error) {
    console.error("Error in postReplyComment API:", error);
    throw error;
  }
}

export function useGetRepliesForComment(idComment: number) {
  const URL = `${endpoints.comment.replyCommentList}/${idComment}`;

  const { data, isLoading, error, isValidating, mutate } = useSWR<
    ReplyComment[]
  >(URL, fetcher1);

  const memoizedValue = useMemo(
    () => ({
      replies: data || [],
      replyLoading: isLoading,
      replyError: error,
      replyValidating: isValidating,
      replyEmpty: !isLoading && !data?.length,
    }),
    [data, error, isLoading, isValidating, mutate]
  );
  return memoizedValue;
}
export async function deleteComment(commentId: number) {
  const URL = endpoints.comment.list;
  return await axiosInstance1.delete(`${endpoints.comment.list}/${commentId}`);
}
export async function toggleLike(commentId: number) {
  return await axiosInstance1.post(
    `${endpoints.comment.toggleLike}/${commentId}`
  );
}
export async function deleteReplyComment(replyId: number) {
  const URL = `${endpoints.comment.deleteReply}/${replyId}`;
  try {
    return await axiosInstance1.delete(URL);
  } catch (error) {
    console.error("Error deleting reply comment:", error);
    throw error;
  }
}
