import React, { useState, useEffect } from "react";
import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Avatar from "@mui/material/Avatar";
import InputBase from "@mui/material/InputBase";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
import Iconify from "@/shared/components/iconify";
import { useMockedUser } from "@/hooks/use-mocked-user";
import { getTokenInfo } from "@/utils/token";
import { CommentReplyItem, ReplyComment } from "@/contexts/types/tasks";
import { useGetRepliesForComment, useGetComments } from "@/shared/api/comment";
import { axiosInstance } from "@/utils/axios";
type Props = {
  idComment: number;
  onReplyComment: (Commnent: CommentReplyItem) => void;
};

export default function ReplyCommentInput({
  idComment,
  onReplyComment,
}: Props) {
  const { user1 } = useMockedUser();
  const [commentText, setCommentText] = useState("");
  const [commentType, setCommentType] = useState("PUBLIC");
  const { replies } = useGetRepliesForComment(idComment);

  const [listData, setListData] = useState<ReplyComment[]>(replies || []);

  useEffect(() => {
    if (replies.length) {
      setListData(replies);
    }
  }, [replies]);

  const fetchUserId = async (): Promise<number | null> => {
    const email = localStorage.getItem("email");
    if (!email) {
      console.error("Email not found in localStorage");
      return null;
    }

    try {
      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      console.log("Fetched user ID:", userResponse.data.id);
      return userResponse.data.id;
    } catch (error) {
      console.error("Error fetching user ID:", error);
      return null;
    }
  };

  function displayUserName() {
    try {
      const token = localStorage.getItem("token");
      if (token) {
        const tokenInfo = getTokenInfo(token);
        return tokenInfo.isValid
          ? tokenInfo.name || "Unknown User"
          : "Session Expired";
      }
    } catch (error) {
      console.error("Error fetching user name from token:", error);
    }
    return "Unknown User";
  }

  const handReplyComment = async () => {
    if (commentText.trim()) {
      const userName = displayUserName();
      try {
        const userId = await fetchUserId();

        if (!userId) {
          console.error("User ID is missing, cannot submit reply");
          return;
        }

        const newComment = {
          commentId: idComment,
          message: commentText,
          messageType: commentType,
          createdAt: new Date().toISOString(),
          tagUser: userName,
          idUser: userId,
          isLiked: false,
        };

        console.log("Sending new comment:", newComment);

        await onReplyComment(newComment);

        // Reset the form
        setCommentText("");
        setCommentType("PUBLIC");
      } catch (error) {
        console.error("Error in postReplyComment API:", error);
      }
    }
  };
  const handlePrivateCommentClick = () => {
    setCommentType("PRIVATE");
  };

  return (
    <Stack
      direction="row"
      spacing={1}
      sx={{
        py: 2,
        px: 2,
      }}
    >
      <Avatar alt={user1?.displayName}>
        {user1?.displayName?.charAt(0).toUpperCase()}
      </Avatar>

      <Paper
        variant="outlined"
        sx={{ p: 1, flexGrow: 1, bgcolor: "transparent" }}
      >
        <InputBase
          fullWidth
          multiline
          rows={2}
          placeholder="Reply a message"
          value={commentText}
          onChange={(e) => setCommentText(e.target.value)}
          sx={{ px: 1 }}
        />

        <Stack direction="row" alignItems="center">
          <Stack direction="row" flexGrow={1}>
            <Tooltip title="private comment">
              <IconButton
                onClick={handlePrivateCommentClick}
                sx={{
                  color: commentType === "PRIVATE" ? "primary.main" : "inherit",
                }}
              >
                <Iconify icon="ri:chat-private-fill" />
              </IconButton>
            </Tooltip>
            <Tooltip title="mention">
              <IconButton>
                <Iconify icon="ci:mention" />
              </IconButton>
            </Tooltip>
          </Stack>

          <Button variant="contained" onClick={handReplyComment}>
            Reply
          </Button>
        </Stack>
      </Paper>
    </Stack>
  );
}
