import {
  postReplyComment,
  useGetRepliesForComment,
  deleteReplyComment,
} from "@/shared/api/comment";
import {
  Stack,
  Avatar,
  Typography,
  Tooltip,
  IconButton,
  Divider,
  MenuItem,
  Menu,
} from "@mui/material";
import { useEffect, useState } from "react";
import Iconify from "@/shared/components/iconify";
import { fToNow } from "@/utils/format-time";
import { CommentReplyItem, ReplyComment } from "@/contexts/types/tasks";
import ReplyCommentInput from "./input-reply-comment";
import { useGetCollaborators } from "@/shared/api/project";
import { collaborator } from "@/contexts/types/Project";
import Box from "@mui/material/Box";
import axios, { axiosInstance } from "@/utils/axios";

type Props = {
  idComment: number;
  setReplyingToCommentId: (state: null) => void;
  replyingToCommentId: null | undefined | number;
};

export default function ReplyCommentList({
  idComment,
  setReplyingToCommentId,
  replyingToCommentId,
}: Props) {
  const { replies } = useGetRepliesForComment(idComment);
  const [isLoadingReplies, setIsLoadingReplies] = useState(true);

  const [listData, setListData] = useState<ReplyComment[]>(replies || []);
  const { collaborators } = useGetCollaborators();
  const [collaboratorData, setCollaboratorData] = useState<collaborator[]>(
    collaborators || []
  );
  const [replyLikeCount, setReplyLikeCount] = useState<{
    [key: number]: number;
  }>({});
  const [replyLiked, setReplyLiked] = useState<{ [key: number]: boolean }>({});
  const [usersWhoLikedReply, setUsersWhoLikedReply] = useState<{
    [key: number]: string[];
  }>({});
  const [showUsersWhoLikedReply, setShowUsersWhoLikedReply] = useState<
    number | null
  >(null);
  const [activeReplyId, setActiveReplyId] = useState<number | null>(null);
  const [anchorElReply, setAnchorElReply] = useState<null | HTMLElement>(null);
  const [replyCollaborators, setReplyCollaborators] = useState<{ [key: number]: any }>({});

  const handleOpenMenu = (
    event: React.MouseEvent<HTMLElement>,
    replyId: number
  ) => {
    setAnchorElReply(event.currentTarget);
    setActiveReplyId(replyId);
  };

  const handleCloseMenu = () => {
    setAnchorElReply(null);
    setActiveReplyId(null);
  };

  const toggleUsersWhoLikedReply = (replyId: number) => {
    setShowUsersWhoLikedReply((prev) => (prev === replyId ? null : replyId));
  };

  const fetchReplyLikes = async (replyId: number) => {
    try {
      const likeCountResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/count`,
        { params: { entityId: replyId, entityType: "REPLY" } }
      );

      setReplyLikeCount((prev) => ({
        ...prev,
        [replyId]: likeCountResponse.data,
      }));

      const email = localStorage.getItem("email");
      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      const userId = userResponse.data.id;

      const likeStatusResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/status`,
        { params: { entityId: replyId, entityType: "REPLY", userId } }
      );

      setReplyLiked((prev) => ({
        ...prev,
        [replyId]: likeStatusResponse.data,
      }));

      const userIdsResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/user-ids`,
        { params: { entityId: replyId, entityType: "REPLY" } }
      );

      const userDetailsPromises = userIdsResponse.data.map((userId: number) =>
        axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/${userId}`
        )
      );

      const usersDetailsResponses = await Promise.all(userDetailsPromises);

      const users = usersDetailsResponses.map((response) => {
        const { firstName, lastName } = response.data;
        return `${firstName} ${lastName}`;
      });

      setUsersWhoLikedReply((prev) => ({ ...prev, [replyId]: users }));
    } catch (error) {
      console.error("Error fetching reply likes:", error);
    }
  };
  const handleToggleLikeReply = async (replyId: number) => {
    try {
      const email = localStorage.getItem("email");
      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      const userId = userResponse.data.id;

      if (replyLiked[replyId]) {
        await axiosInstance.delete(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/remove`,
          {
            params: { entityId: replyId, entityType: "REPLY", userId },
          }
        );

        setReplyLikeCount((prev) => ({
          ...prev,
          [replyId]: Math.max((prev[replyId] || 0) - 1, 0),
        }));
        setReplyLiked((prev) => ({ ...prev, [replyId]: false }));
      } else {
        await axiosInstance.post(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/add`,
          {
            entityId: replyId,
            entityType: "REPLY",
            userId,
          }
        );

        setReplyLikeCount((prev) => ({
          ...prev,
          [replyId]: (prev[replyId] || 0) + 1,
        }));
        setReplyLiked((prev) => ({ ...prev, [replyId]: true }));
      }

      await fetchReplyLikes(replyId);
    } catch (error) {
      console.error("Error toggling like for reply:", error);
    }
  };

  useEffect(() => {
    if (collaborators.length) {
      setCollaboratorData(collaborators);
    }
  }, [collaborators]);

  function getCollaboratorById(collaboratorId: number) {
    const collaborator = collaboratorData.find(
      (collaborator) => collaborator.id === collaboratorId
    );
    if (!collaborator) {
      return { user: { firstName: "Unknown", lastName: "User" } }; // Placeholder collaborator
    }
    return collaborator;
  }

  useEffect(() => {
    if (replies) {
      setListData(replies);
      setIsLoadingReplies(false);
      replies.forEach((reply) => fetchReplyLikes(reply.id));
    }
  }, [replies]);

  const onReplyComment = async (newComment: CommentReplyItem) => {
    try {
      const email = localStorage.getItem("email");
      const agencyId = localStorage.getItem("selectedAgency");

      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/${email}/${agencyId}`
      );
      const userId = response.data.id;

      const replyPayload = {
        ...newComment,
        idUser: userId
      };

      const replyResponse = await postReplyComment(replyPayload);
      setReplyingToCommentId(null);
      setListData((prevData) => [...prevData, replyResponse.data]);
    } catch (error) {
      console.error("Error adding reply:", error);
    }
  };
  const handleDeleteReply = async (replyId: number) => {
    try {
      await deleteReplyComment(replyId);
      setListData((prevData) =>
        prevData.filter((reply) => reply.id !== replyId)
      );
    } catch (error) {
      console.error("Error deleting reply:", error);
    }
  };

  useEffect(() => {
    const fetchCollaborators = async () => {
      for (const reply of listData) {
        if (reply.idUser && !replyCollaborators[reply.idUser]) {
          try {
            const response = await axiosInstance.get(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
              {
                params: { Id: reply.idUser }
              }
            );
            setReplyCollaborators(prev => ({
              ...prev,
              [reply.idUser as number]: response.data
            }));
          } catch (error) {
            console.error('Error fetching collaborator:', error);
          }
        }
      }
    };

    fetchCollaborators();
  }, [listData]);

  if (isLoadingReplies) {
    return <div>Loading replies...</div>;
  }

  return (
    <Stack
      spacing={3}
      flexGrow={1}
      sx={{
        py: 3,
        px: 2.5,
      }}
    >
      {replyingToCommentId === idComment && (
        <ReplyCommentInput
          idComment={idComment}
          onReplyComment={onReplyComment}
        />
      )}

      {listData.map((comment: ReplyComment) => {
        const collaborator = replyCollaborators[comment.idUser as number];
        
        return (
          <Stack
            key={comment.id}
            direction="row"
            spacing={2}
            sx={{
              border: "1px solid",
              borderColor: "divider",
              borderRadius: 2,
              p: 2,
              margin: "8px 0",
            }}
          >
            <Avatar>
              {collaborator?.user?.firstName?.charAt(0).toUpperCase()}
              {collaborator?.user?.lastName?.charAt(0).toUpperCase()}
            </Avatar>

            <Stack spacing={0.5} flexGrow={1}>
              <Stack
                direction="row"
                alignItems="center"
                justifyContent="space-between"
              >
                <Typography variant="subtitle2">
                  {`${collaborator?.user?.firstName} ${collaborator?.user?.lastName}`}
                </Typography>
                <Typography variant="caption" sx={{ color: "text.disabled" }}>
                  {fToNow(comment.createdAt)}
                </Typography>
              </Stack>

              <Typography variant="body2">{comment.message}</Typography>
              <Divider sx={{ my: 1 }} />
              <Stack
                direction="row"
                justifyContent="flex-end"
                alignItems="center"
                flexGrow={1}
              >
                <Tooltip title="Like">
                  <IconButton
                    onClick={() => handleToggleLikeReply(comment.id)}
                    color={replyLiked[comment.id] ? "info" : "default"}
                  >
                    <Iconify icon="ic:round-thumb-up" />
                  </IconButton>
                </Tooltip>
                <Typography variant="caption">
                  {replyLikeCount[comment.id] || 0} Likes
                </Typography>

                <Tooltip title="Who liked this?">
                  <IconButton
                    onClick={(event) => handleOpenMenu(event, comment.id)}
                  >
                    <Iconify icon="ic:outline-info" />
                  </IconButton>
                </Tooltip>

                <Menu
                  anchorEl={anchorElReply}
                  open={Boolean(anchorElReply) && activeReplyId === comment.id}
                  onClose={handleCloseMenu}
                  anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
                  transformOrigin={{ vertical: "top", horizontal: "left" }}
                >
                  {(usersWhoLikedReply[comment.id] || []).length > 0 ? (
                    usersWhoLikedReply[comment.id].map((user, index) => (
                      <MenuItem key={index}>
                        <Typography variant="body2">{user}</Typography>
                      </MenuItem>
                    ))
                  ) : (
                    <MenuItem>
                      <Typography variant="body2" color="textSecondary">
                        No likes yet.
                      </Typography>
                    </MenuItem>
                  )}
                </Menu>

                <Tooltip title="Delete">
                  <IconButton onClick={() => handleDeleteReply(comment.id)}>
                    <Iconify icon="solar:trash-bin-trash-bold" />
                  </IconButton>
                </Tooltip>
              </Stack>
            </Stack>
          </Stack>
        );
      })}
    </Stack>
  );
}
