import { Edit2 } from "iconsax-react";
import moment from "moment-jalaali";
import { type FC, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "../../../../../components/Toast";
import TrashWithConfrim from "../../../../../components/TrashWithConfrim";
import { ErrorType } from "../../../../../helpers/types";
import { useDeleteTaskComment, useUpdateTaskComment } from "../../../task/hooks/useTaskCommentData";
import type { TaskCommentType } from "../../../task/types/TaskCommentTypes";
import UserAvatar from "../../UserAvatar";

type Props = {
  comment: TaskCommentType;
  taskId: string;
};

const CommentItem: FC<Props> = ({ comment, taskId }) => {
  const { t } = useTranslation("global");
  const [isEditing, setIsEditing] = useState(false);
  const [content, setContent] = useState(comment.content);
  const updateComment = useUpdateTaskComment();
  const deleteComment = useDeleteTaskComment();

  const authorName = comment.user
    ? `${comment.user.firstName} ${comment.user.lastName}`.trim()
    : t("taskmanager.task_detail.unknown_user");

  const handleSave = () => {
    const trimmedContent = content.trim();
    if (!trimmedContent || trimmedContent === comment.content) {
      setIsEditing(false);
      setContent(comment.content);
      return;
    }

    updateComment.mutate(
      { id: comment.id, params: { content: trimmedContent }, taskId },
      {
        onSuccess: () => {
          toast(t("success"), "success");
          setIsEditing(false);
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], "error");
        },
      },
    );
  };

  const handleCancel = () => {
    setContent(comment.content);
    setIsEditing(false);
  };

  const handleDelete = () => {
    deleteComment.mutate(
      { id: comment.id, taskId },
      {
        onSuccess: () => {
          toast(t("success"), "success");
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], "error");
        },
      },
    );
  };

  return (
    <div className="bg-white/25 rounded-xl p-3">
      <div className="flex items-start gap-2">
        <UserAvatar src={comment.user?.profilePic} alt={authorName} className="size-7" />

        <div className="flex-1 min-w-0">
          <div className="flex items-center justify-between gap-2">
            <div className="text-xs font-medium truncate">{authorName}</div>
            <div className="text-[10px] text-description shrink-0">
              {moment(comment.createdAt).format("jYYYY/jMM/jDD HH:mm")}
            </div>
          </div>

          {isEditing ? (
            <div className="mt-2">
              <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                rows={3}
                className="w-full bg-white/50 rounded-lg px-3 py-2 text-xs outline-none resize-none"
                autoFocus
              />
              <div className="flex gap-2 mt-2">
                <button
                  type="button"
                  onClick={handleSave}
                  disabled={updateComment.isPending || !content.trim()}
                  className="h-7 px-3 rounded-lg bg-[#292D32] text-white text-[11px] disabled:opacity-50"
                >
                  {t("save")}
                </button>
                <button
                  type="button"
                  onClick={handleCancel}
                  disabled={updateComment.isPending}
                  className="h-7 px-3 rounded-lg bg-white/50 text-[#292D32] text-[11px] border border-white"
                >
                  {t("cancel")}
                </button>
              </div>
            </div>
          ) : (
            <div className="mt-1 text-xs leading-6 whitespace-pre-line break-words">{comment.content}</div>
          )}
        </div>

        {!isEditing ? (
          <div className="flex items-center gap-1 shrink-0">
            <button type="button" onClick={() => setIsEditing(true)} className="cursor-pointer">
              <Edit2 size={16} color="#0047FF" />
            </button>
            <TrashWithConfrim onDelete={handleDelete} isLoading={deleteComment.isPending} size={16} color="#FF0000" />
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default CommentItem;
