import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "../../../../../components/Toast";
import { ErrorType } from "../../../../../helpers/types";
import { useCreateTaskComment, useGetTaskComments } from "../../../task/hooks/useTaskCommentData";
import CommentItem from "./CommentItem";

type Props = {
  taskId: string;
  enabled?: boolean;
};

const CommentList: FC<Props> = ({ taskId, enabled = true }) => {
  const { t } = useTranslation("global");
  const [content, setContent] = useState("");
  const getComments = useGetTaskComments(taskId, enabled);
  const createComment = useCreateTaskComment();

  const comments = getComments.data?.data ?? [];

  const handleSubmit = () => {
    const trimmedContent = content.trim();
    if (!trimmedContent) return;

    createComment.mutate(
      { content: trimmedContent, taskId },
      {
        onSuccess: () => {
          toast(t("success"), "success");
          setContent("");
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], "error");
        },
      },
    );
  };

  return (
    <div className="mt-6">
      <div className="text-sm font-bold">{t("taskmanager.task_detail.comments")}</div>

      <div className="mt-3 relative bg-white/25 rounded-xl">
        <button
          type="button"
          onClick={handleSubmit}
          disabled={createComment.isPending || !content.trim()}
          className="absolute top-2 left-2 z-10 h-7 px-2.5 rounded-lg bg-[#292D32] text-white text-[11px] disabled:opacity-50"
        >
          {t("taskmanager.task_detail.add_comment")}
        </button>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder={t("taskmanager.task_detail.comment_placeholder")}
          rows={3}
          className="w-full bg-transparent rounded-xl px-4 pt-4 pb-3 text-xs outline-none resize-none placeholder:text-description"
        />
      </div>

      {getComments.isPending ? (
        <div className="mt-3 text-[10px] text-description text-center py-2">{t("loading")}</div>
      ) : comments.length === 0 ? (
        <div className="mt-3 text-[10px] text-description">{t("taskmanager.task_detail.no_comments")}</div>
      ) : (
        <div className="mt-3 flex flex-col gap-2">
          {comments.map((comment) => (
            <CommentItem key={comment.id} comment={comment} taskId={taskId} />
          ))}
        </div>
      )}
    </div>
  );
};

export default CommentList;
