import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import axios from "axios";
import formatDistance from "date-fns/formatDistance";
import { Link, useLocation, useParams } from "react-router-dom";

import FavoriteIcon from "@mui/icons-material/Favorite";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import BookmarkBorderIcon from "@mui/icons-material/BookmarkBorder";
import BookmarkIcon from "@mui/icons-material/Bookmark";
import AccountCircleRoundedIcon from "@mui/icons-material/AccountCircleRounded";
import ChatBubbleOutlineRoundedIcon from "@mui/icons-material/ChatBubbleOutlineRounded";
import RepeatIcon from "@mui/icons-material/Repeat";
import RepeatOnIcon from "@mui/icons-material/RepeatOn";

const Tweet = ({ tweet, setData }) => {
  const { currentUser } = useSelector((state) => state.user);
  const [userData, setUserData] = useState(null);
  const [dateStr, setDateStr] = useState("");
  const [votedOption, setVotedOption] = useState(null);

  const location = useLocation().pathname;
  const { username } = useParams();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const findUser = await axios.get(`/users/find/${tweet.username}`);
        setUserData(findUser.data);
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, [tweet.username, tweet.likes, tweet.retweets]);

  useEffect(() => {
    setDateStr(formatDistance(new Date(tweet.createdAt), new Date()));
  }, [tweet.createdAt]);

  const handleLikeUnlike = async (e) => {
    e.preventDefault();
    try {
      const like = await axios.put(`/tweets/${tweet._id}/like`);
      if (location.includes("profile")) {
        const newData = await axios.get(`/tweets/${username}/tweets`);
        setData(newData.data);
      } else if (location.includes("explore")) {
        const newData = await axios.get(`/tweets/explore/`);
        setData(newData.data);
      } else {
        const newData = await axios.get(`/tweets/timeline`);
        setData(newData.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleRetweet = async () => {
    try {
      await axios.put(`/tweets/${tweet._id}/retweet`);
      if (location.includes("profile")) {
        const newData = await axios.get(`/tweets/${username}/tweets`);
        setData(newData.data);
      } else if (location.includes("explore")) {
        const newData = await axios.get(`/tweets/explore/`);
        setData(newData.data);
      } else {
        const newData = await axios.get(`/tweets/timeline`);
        setData(newData.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleBookmark = async () => {
    try {
      await axios.put(`/tweets/${tweet._id}/bookmark`);
      if (location.includes("profile")) {
        const newData = await axios.get(`/tweets/${username}/tweets`);
        setData(newData.data);
      } else if (location.includes("explore")) {
        const newData = await axios.get(`/tweets/explore/`);
        setData(newData.data);
      } else {
        const newData = await axios.get(`/tweets/timeline`);
        setData(newData.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleVoteOption = async (option) => {
    try {
      const response = await axios.put(`/tweets/${tweet._id}/vote`, { option });
      setVotedOption(option);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      {userData && (
        <div className="flex space-x-2">
          <Link to={`/profile/${userData.username}`}>
            <img
              className="w-10 h-10 rounded-full object-cover"
              src={!userData.profilePicture ? "default_profile_picture_url" : userData.profilePicture}
              alt=""
            />
          </Link>
          <Link to={`/profile/${userData.username}`}>
            <h2 className="font-bold">{userData.firstname} {userData.lastname}</h2>
          </Link>
          <Link to={`/profile/${userData.username}`}>
            <span className="font-normal">@{userData.username}</span>
          </Link>
          <p>-{dateStr}</p>
        </div>
      )}

      <p>{tweet.content}</p>

      {tweet.options && tweet.options.length > 0 && (
        <div>
          <h3>Options:</h3>
          <ul>
            {tweet.options.map((option, index) => (
              <li key={index}>
                <button disabled={votedOption === option} onClick={() => handleVoteOption(option)}>{option}</button>
                <span>{tweet.votes[option]}</span>
              </li>
            ))}
          </ul>
        </div>
      )}

      {tweet.media && (
        tweet.media.includes(".mp4") || tweet.media.includes(".avi") || tweet.media.includes(".mov") || tweet.media.includes(".wmv") || tweet.media.includes(".flv") || tweet.media.includes(".mkv") ? (
          <video className="w-full h-80 object-cover rounded-lg" controls src={tweet.media} />
        ) : (
          <img className="w-full h-80 object-cover rounded-lg" src={tweet.media} alt="Media" />
        )
      )}

      <button onClick={handleLikeUnlike}>
        {tweet.likes.includes(currentUser.username) ? (
          <FavoriteIcon className="mr-2 my-2 cursor-pointer" />
        ) : (
          <FavoriteBorderIcon className="mr-2 my-2 cursor-pointer" />
        )}
        {tweet.likes.length}
      </button>

      <button onClick={handleRetweet}>
        {tweet.retweets.includes(currentUser.username) ? (
          <RepeatOnIcon className="mr-2 my-2 cursor-pointer" />
        ) : (
          <RepeatIcon className="mr-2 my-2 cursor-pointer" />
        )}
        {tweet.retweets.length}
      </button>

      <Link to={`/tweets/find/${tweet._id}`}>
        <button>
          <ChatBubbleOutlineRoundedIcon />
          {tweet.comments.length}
        </button>
      </Link>

      <button onClick={handleBookmark}>
        {tweet.bookmarks.includes(currentUser.username) ? (
          <BookmarkIcon />
        ) : (
          <BookmarkBorderIcon />
        )}
      </button>
    </div>
  );
};

export default Tweet;