// import {connect, useDispatch} from "react-redux";
// import "../../App.css";
// import {useHistory} from "react-router-dom";
// import EditProfile from "./editeProfile";
// import EditPost from "./editePost";
// import React, {useEffect, useState} from "react";
// import {Box} from "@mui/material";
// import {actionPostById, actionShowFollowing, delete_post, actionShowFollowers} from "../../actions";
// import {ConnectUploadPhotoForm} from "../UploadPhoto";
// import {actionSubscribe, getUserFollowing, actionUnfollow} from "../../actions/user";
// import {
//     UserPage,
//     StyledUserProfile,
//     ProfileAvatar,
//     UserProfileDescription,
//     ProfileName,
//     ProfileInfo,
//     UserPagePosts,
//     PostImage
// } from "./profile.module";
// import PostDetails from "./postDEtails";
//
// const UserProfile = ({
//                          match: {
//                              params: {id},
//                          },
//                          onProfile,
//                          state,
//                      }) => {
//
//     const dispatch = useDispatch()
//
//
//     let posts = state?.promise?.PostById?.payload?.data?.PostFind;
//     let token = state?.auth?.payload?.id;
//
//     const [followers, setFollowers] = useState([]);
//     const [showModal, setShowModal] = useState(false);
//     const [isFollowingModal, setIsFollowingModal] = useState(false);
//     const [editeModalProfile, setEditeModalProfile] = useState(false);
//     const [statePosts, setStatePosts] = useState([]);
//
//     useEffect(() => {
//         setStatePosts(posts)
//     })
//
//     const [following, setFollowing] = useState([]);
//     const [followingIds, setFollowingIds] = useState([]);
//     const [isFollowing, setIsFollowing] = useState('loading');
//
//     useEffect(() => {
//         const followersArray = posts?.[0]?.owner?.followers || [];
//         setIsFollowing(followersArray.some(f => f._id === token));
//     }, [posts, token]);
//
//     const handleDeletePost = (id) => {
//         delete_post(id)
//         window.location.reload()
//     }
//
//     const [showEditeModal, setShowEditeModal] = useState(false)
//     const [editedPost, setEditedPost] = useState()
//
//     const handleEditePost = (post) => {
//         console.log(post)
//         setShowEditeModal(true)
//         setEditedPost(post)
//     }
//
//     const handleCloseModalEditePost = () => {
//         setShowEditeModal(false)
//     }
//
//     const history = useHistory();
//
//
//     const showFollowers = async () => {
//         setFollowers([]);
//         const response = (await actionShowFollowers(id)(dispatch));
//         const followersData = response?.data?.UserFindOne?.followers ?? [];
//         setFollowers(followersData);
//         setShowModal(!showModal);
//         setIsFollowingModal(false);
//     };
//
//     const showFollowing = async () => {
//         setFollowers([]);
//         const response = (await actionShowFollowing(id)(dispatch));
//         const followersData = response?.data?.UserFindOne?.following ?? [];
//         setFollowers(followersData);
//         setShowModal(!showModal);
//         setIsFollowingModal(true);
//     };
//
//     const handleFollowerClick = (follower) => {
//         history.push(`/user/${follower._id}`);
//         setShowModal(false);
//     };
//
//     useEffect(() => {
//         onProfile(id);
//     }, [id]);
//
//
//     const handleFollowUser = async () => {
//         try {
//             const response = await getUserFollowing(token);
//             const following = response?.data?.UserFindOne?.following;
//             following.push({_id: id});
//             actionSubscribe(token, following);
//         } catch (error) {
//             console.error(error);
//         } finally {
//             window.location.reload()
//         }
//     };
//
//     const handleUnfollowUser = async () => {
//         try {
//             await actionUnfollow(token, id)(dispatch);
//         } finally {
//             window.location.reload();
//         }
//     };
//
//     const handleCloseModal = () => {
//         setShowModal(false);
//     }
//
//     const handleEditeProfile = () => {
//         setEditeModalProfile(true)
//     }
//     const handleCloseModalEdite = () => {
//         setEditeModalProfile(false)
//     }
//
//     const [showPostModal, setShowPostModal] = useState(false)
//
//     const [postDetails, setPostDetails] = useState([])
//
//     const showPost = (post) => {
//         setShowPostModal(true)
//         setPostDetails(post)
//     }
//
//     const closePostDetails = (() => setShowPostModal(false))
//
//
//     return (
//         <UserPage>
//             {showEditeModal && <EditPost post={editedPost} onCloseModall={handleCloseModalEditePost}/>}
//             {showModal &&
//                 <FollowersModal isFollowingModal={isFollowingModal} followers={followers}
//                                 handleFollowerClick={handleFollowerClick} onCloseModal={handleCloseModal}/>}
//             {editeModalProfile &&
//                 <EditProfile nickname={posts?.[0]?.owner?.login} userId={token} onCloseModall={handleCloseModalEdite}/>}
//             {showPostModal && <PostDetails onCloseModall={closePostDetails} post={postDetails}/>}
//             <StyledUserProfile>
//                 {!posts?.[0]?.owner?.avatar?.url && token === id ? (
//                     <Box>
//                         <ConnectUploadPhotoForm/>
//                     </Box>
//                 ) : (
//                     <ProfileAvatar>
//                         <Box
//                             component="img"
//                             src={`../${posts?.[0]?.owner?.avatar?.url}`}
//                             alt="profile-avatar"
//                         />
//                     </ProfileAvatar>
//                 )}
//                 <UserProfileDescription>
//                     <ProfileName>
//                         <p className="profile-login">{`Username: ${posts?.[0]?.owner?.login || state?.auth?.payload?.login
//                         }`}</p>
//                     </ProfileName>
//                     <ProfileInfo>
//                         <Box component="p">{`Posts: ${posts ? posts?.length : "0"}`}</Box>
//                         <Box onClick={showFollowers} component="p">{`Followers: ${posts?.[0]?.owner?.followers
//                             ? posts?.[0]?.owner?.followers?.length
//                             : "0"
//                         }`}</Box>
//                         <Box onClick={showFollowing} component="p">{`Following: ${posts?.[0]?.owner?.following?.length
//                             ? posts?.[0]?.owner?.following.length
//                             : "0"
//                         }`}
//                         </Box>
//                     </ProfileInfo>
//                     {token !== id ?
//                         <div style={{
//                             width: "100%"
//                         }}>
//                             {isFollowing === 'loading' ? (
//                                 <button style={{textAlign: "center"}}>Loading...</button>
//                             ) : isFollowing ? (
//                                 <button className="unflw_btn" onClick={handleUnfollowUser}>Unfollow</button>
//                             ) : (
//                                 <button className="flw_btn" onClick={handleFollowUser}>Follow</button>
//                             )}
//                         </div>
//
//                         :
//                         <button className="edite_profile" onClick={handleEditeProfile}>Edite Profile</button>
//                     }
//                 </UserProfileDescription>
//
//             </StyledUserProfile>
//
//             <UserPagePosts className="user-page-posts">
//                 {statePosts?.map((post) => (
//
//                     <PostImage key={post._id} className="post-image">
//                         <Box onClick={() => showPost(post)}
//                             component="img"
//                             src={`../${post?.images?.[0]?.url}`}
//                             alt="post"
//                         />
//                         {token === id &&
//
//                             <div className="post_tool_block">
//                                 <div onClick={() => handleEditePost(post)}>
//                                     <svg style={{width: '20px', height: '20px'}} viewBox="0 0 24 24" fill="none"
//                                          xmlns="http://www.w3.org/2000/svg">
//                                         <path d="M13 21H21" stroke="#323232" stroke-width="2" stroke-linecap="round"
//                                               stroke-linejoin="round"/>
//                                         <path
//                                             d="M20.0651 7.39423L7.09967 20.4114C6.72438 20.7882 6.21446 21 5.68265 21H4.00383C3.44943 21 3 20.5466 3 19.9922V18.2987C3 17.7696 3.20962 17.2621 3.58297 16.8873L16.5517 3.86681C19.5632 1.34721 22.5747 4.87462 20.0651 7.39423Z"
//                                             stroke="#323232" stroke-width="2" stroke-linecap="round"
//                                             stroke-linejoin="round"/>
//                                         <path d="M15.3096 5.30981L18.7273 8.72755" stroke="#323232" stroke-width="2"
//                                               stroke-linecap="round" stroke-linejoin="round"/>
//                                         <path opacity="0.1"
//                                               d="M18.556 8.90942L7.09967 20.4114C6.72438 20.7882 6.21446 21 5.68265 21H4.00383C3.44943 21 3 20.5466 3 19.9922V18.2987C3 17.7696 3.20962 17.2621 3.58297 16.8873L15.0647 5.35974C15.0742 5.4062 15.0969 5.45049 15.1329 5.48653L18.5506 8.90426C18.5524 8.90601 18.5542 8.90773 18.556 8.90942Z"
//                                               fill="#323232"/>
//                                     </svg>
//                                 </div>
//
//                                 <div onClick={() => handleDeletePost(post._id)}>
//                                     <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none"
//                                          xmlns="http://www.w3.org/2000/svg"
//                                          style={{width: '20px', height: '20px'}}>
//                                         <path
//                                             d="M12 22C17.5 22 22 17.5 22 12C22 6.5 17.5 2 12 2C6.5 2 2 6.5 2 12C2 17.5 6.5 22 12 22Z"
//                                             stroke="#292D32" stroke-width="1.5" stroke-linecap="round"
//                                             stroke-linejoin="round"/>
//                                         <g opacity="0.4">
//                                             <path d="M9.16992 14.8299L14.8299 9.16992" stroke="#292D32"
//                                                   stroke-width="1.5"
//                                                   stroke-linecap="round" stroke-linejoin="round"/>
//                                             <path d="M14.8299 14.8299L9.16992 9.16992" stroke="#292D32"
//                                                   stroke-width="1.5"
//                                                   stroke-linecap="round" stroke-linejoin="round"/>
//                                         </g>
//                                     </svg>
//                                 </div>
//                             </div>
//                         }
//                         <div>
//                             {post.title ?
//                                 <div>
//                                     <h5>{post.title}</h5>
//                                     <p>{post.text}</p></div>
//                                 : <p>empty...</p>
//                             }
//                         </div>
//                     </PostImage>
//
//                 ))}
//             </UserPagePosts>
//         </UserPage>
//     );
// };
//
// const FollowersModal = ({followers, isFollowingModal, onCloseModal, handleFollowerClick}) => {
//     return (
//         <div className="modal">
//             <div className="modal_block" style={{width: '500px'}}>
//                 <h2>{isFollowingModal ? "Following" : "Followers"}</h2>
//                 {followers.length > 0 ? (
//                     <div className="list_followers">
//                         {followers.map((follower) => (
//                             follower.login && (
//                                 <div className="user" key={follower}>
//                                     <img onClick={() => handleFollowerClick(follower)}
//                                          src={`../${follower?.avatar?.url}`}/>
//                                     <h4 onClick={() => handleFollowerClick(follower)}>{follower?.login}</h4>
//                                     <button style={{
//                                         backgroundColor: isFollowingModal ? "#ccc" : "#007bff",
//                                         color: isFollowingModal ? "#000" : "#fff"
//                                     }}>
//                                         {isFollowingModal ? "unfollow" : "follow"}
//                                     </button>
//                                 </div>
//                             )
//                         ))}
//                     </div>
//                 ) : (
//                     <p>No {isFollowingModal ? "following" : "followers"} to show</p>
//                 )}
//                 <button className="close_followers_modal" onClick={onCloseModal}>
//                     x
//                 </button>
//             </div>
//         </div>
//     );
//
// };
//
// export const UserProfileDraw = connect((state) => ({state: state}), {
//     onProfile: actionPostById,
// })(UserProfile);

import { connect, useDispatch } from "react-redux";
import "../../App.css";
import { useHistory } from "react-router-dom";
import EditProfile from "./editeProfile";
import EditPost from "./editePost";
import React, { useEffect, useState } from "react";
import { Box } from "@mui/material";
import { actionPostById, actionShowFollowing, delete_post, actionShowFollowers } from "../../actions";
import { ConnectUploadPhotoForm } from "../UploadPhoto";
import { actionSubscribe, getUserFollowing, actionUnfollow,gqlAboutUser } from "../../actions/user";
import {
    UserPage,
    StyledUserProfile,
    ProfileAvatar,
    UserProfileDescription,
    ProfileName,
    ProfileInfo,
    UserPagePosts,
    PostImage
} from "./profile.module";
import PostDetails from "./postDEtails";

const UserProfile = ({
    match: {
        params: { id },
    },
    onProfile,
    state,
}) => {

    const dispatch = useDispatch()


    let posts = state?.promise?.PostById?.payload?.data?.PostFind;
    let token = state?.auth?.payload?.id;

    const [followers, setFollowers] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [isFollowingModal, setIsFollowingModal] = useState(false);
    const [editeModalProfile, setEditeModalProfile] = useState(false);
    const [statePosts, setStatePosts] = useState([]);
    const [following, setFollowing] = useState([]);
    const [followingIds, setFollowingIds] = useState([]);
    const [isFollowing, setIsFollowing] = useState('loading');
    const [showEditeModal, setShowEditeModal] = useState(false)
    const [editedPost, setEditedPost] = useState()
    const [showPostModal, setShowPostModal] = useState(false)
    const [postDetails, setPostDetails] = useState([])
    const [currentUser,setCurrentUser] = useState()

    useEffect(() => {
        setStatePosts(posts)
    })

    useEffect(() => {
        (async () => {
          const currentUser = (await gqlAboutUser(token)).data.UserFindOne;
          setCurrentUser(currentUser);
        })()
      }, []);

    useEffect(() => {
        const followersArray = posts?.[0]?.owner?.followers || [];
        setIsFollowing(followersArray.some(f => f._id === token));
    }, [posts, token]);

    const handleDeletePost = (id) => {
        delete_post(id)
        window.location.reload()
    }

    const handleEditePost = (post) => {
        console.log(post)
        setShowEditeModal(true)
        setEditedPost(post)
    }

    const handleCloseModalEditePost = () => {
        setShowEditeModal(false)
    }

    const history = useHistory();

    const showFollowers = async () => {
        setFollowers([]);
        const response = (await actionShowFollowers(id)(dispatch));
        const followersData = response?.data?.UserFindOne?.followers ?? [];
        setFollowers(followersData);
        setShowModal(!showModal);
        setIsFollowingModal(false);
    };

    const showFollowing = async () => {
        setFollowers([]);
        const response = (await actionShowFollowing(id)(dispatch));
        const followersData = response?.data?.UserFindOne?.following ?? [];
        setFollowers(followersData);
        setShowModal(!showModal);
        setIsFollowingModal(true);
    };

    const handleFollowerClick = (follower) => {
        history.push(`/user/${follower._id}`);
        setShowModal(false);
    };

    useEffect(() => {
        onProfile(id);
    }, [id]);

    const handleFollowUser = async () => {
        try {
            const response = await getUserFollowing(token);
            const following = response?.data?.UserFindOne?.following;
            following.push({ _id: id });
            actionSubscribe(token, following);
        } catch (error) {
            console.error(error);
        } finally {
            window.location.reload()
        }
    };

    const handleUnfollowUser = async () => {
        try {
            await actionUnfollow(token, id)(dispatch);
        } finally {
            window.location.reload();
        }
    };

    const handleCloseModal = () => {
        setShowModal(false);
    }

    const handleEditeProfile = () => {
        setEditeModalProfile(true)
    }
    const handleCloseModalEdite = () => {
        setEditeModalProfile(false)
    }

    const showPost = (post) => {
        setShowPostModal(true)
        setPostDetails(post)
    }

    const closePostDetails = (() => setShowPostModal(false))

    return (
        <UserPage>
            {showEditeModal && <EditPost post={editedPost} onCloseModall={handleCloseModalEditePost} />}
            {showModal &&
                <FollowersModal isFollowingModal={isFollowingModal} followers={followers}
                    handleFollowerClick={handleFollowerClick} onCloseModal={handleCloseModal} />}
            {editeModalProfile &&
                <EditProfile nickname={posts?.[0]?.owner?.login} userId={token} onCloseModall={handleCloseModalEdite} />}
            {showPostModal && <PostDetails onCloseModall={closePostDetails} currentUser={currentUser} post={postDetails} />}
            <StyledUserProfile>
                {!posts?.[0]?.owner?.avatar?.url && token === id ? (
                    <Box>
                        <ConnectUploadPhotoForm />
                    </Box>
                ) : (
                    <ProfileAvatar>
                        <Box
                            component="img"
                            src={`../${posts?.[0]?.owner?.avatar?.url}`}
                            alt="profile-avatar"
                        />
                    </ProfileAvatar>
                )}
                <UserProfileDescription>
                    <ProfileName>
                        <p className="profile-login">{`Username: ${posts?.[0]?.owner?.login || state?.auth?.payload?.login
                            }`}</p>
                    </ProfileName>
                    <ProfileInfo>
                        <Box component="p">{`Posts: ${posts ? posts?.length : "0"}`}</Box>
                        <Box onClick={showFollowers} component="p">{`Followers: ${posts?.[0]?.owner?.followers
                            ? posts?.[0]?.owner?.followers?.length
                            : "0"
                            }`}</Box>
                        <Box onClick={showFollowing} component="p">{`Following: ${posts?.[0]?.owner?.following?.length
                            ? posts?.[0]?.owner?.following.length
                            : "0"
                            }`}
                        </Box>
                    </ProfileInfo>
                    {token !== id ?
                        <div style={{
                            width: "100%"
                        }}>
                            {isFollowing === 'loading' ? (
                                <button style={{ textAlign: "center" }}>Loading...</button>
                            ) : isFollowing ? (
                                <button className="unflw_btn" onClick={handleUnfollowUser}>Unfollow</button>
                            ) : (
                                <button className="flw_btn" onClick={handleFollowUser}>Follow</button>
                            )}
                        </div>

                        :
                        <button className="edite_profile" onClick={handleEditeProfile}>Edite Profile</button>
                    }
                </UserProfileDescription>

            </StyledUserProfile>

            <UserPagePosts className="user-page-posts">
                {statePosts?.map((post) => (

                    <PostImage key={post._id} className="post-image">
                        <Box onClick={() => showPost(post)}
                            component="img"
                            src={`../${post?.images?.[0]?.url}`}
                            alt="post"
                            style={{ height: '260px' }}
                        />
                        {token === id &&

                            <div className="post_tool_block">
                                <div onClick={() => handleEditePost(post)}>
                                    <svg style={{ width: '20px', height: '20px' }} viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg">
                                        <path d="M13 21H21" stroke="#323232" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <path
                                            d="M20.0651 7.39423L7.09967 20.4114C6.72438 20.7882 6.21446 21 5.68265 21H4.00383C3.44943 21 3 20.5466 3 19.9922V18.2987C3 17.7696 3.20962 17.2621 3.58297 16.8873L16.5517 3.86681C19.5632 1.34721 22.5747 4.87462 20.0651 7.39423Z"
                                            stroke="#323232" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <path d="M15.3096 5.30981L18.7273 8.72755" stroke="#323232" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round" />
                                        <path opacity="0.1"
                                            d="M18.556 8.90942L7.09967 20.4114C6.72438 20.7882 6.21446 21 5.68265 21H4.00383C3.44943 21 3 20.5466 3 19.9922V18.2987C3 17.7696 3.20962 17.2621 3.58297 16.8873L15.0647 5.35974C15.0742 5.4062 15.0969 5.45049 15.1329 5.48653L18.5506 8.90426C18.5524 8.90601 18.5542 8.90773 18.556 8.90942Z"
                                            fill="#323232" />
                                    </svg>
                                </div>

                                <div onClick={() => handleDeletePost(post._id)}>
                                    <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg"
                                        style={{ width: '20px', height: '20px' }}>
                                        <path
                                            d="M12 22C17.5 22 22 17.5 22 12C22 6.5 17.5 2 12 2C6.5 2 2 6.5 2 12C2 17.5 6.5 22 12 22Z"
                                            stroke="#292D32" stroke-width="1.5" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <g opacity="0.4">
                                            <path d="M9.16992 14.8299L14.8299 9.16992" stroke="#292D32"
                                                stroke-width="1.5"
                                                stroke-linecap="round" stroke-linejoin="round" />
                                            <path d="M14.8299 14.8299L9.16992 9.16992" stroke="#292D32"
                                                stroke-width="1.5"
                                                stroke-linecap="round" stroke-linejoin="round" />
                                        </g>
                                    </svg>
                                </div>
                            </div>
                        }
                        <div style={{ marginTop: '20px' }}>
                            {post.title ?
                                <div>
                                    <h5>{post.title}</h5>
                                    <p>{post.text}</p></div>
                                : <p>empty...</p>
                            }
                        </div>
                    </PostImage>

                ))}
            </UserPagePosts>
        </UserPage>
    );
};

const FollowersModal = ({ followers, isFollowingModal, onCloseModal, handleFollowerClick }) => {
    return (
        <div className="modal">
            <div className="modal_block" style={{ width: '500px' }}>
                <h2>{isFollowingModal ? "Following" : "Followers"}</h2>
                {followers.length > 0 ? (
                    <div className="list_followers">
                        {followers.map((follower) => (
                            follower.login && (
                                <div className="user" key={follower}>
                                    <img onClick={() => handleFollowerClick(follower)}
                                        src={`../${follower?.avatar?.url}`}
                                        style={{ width: '40px', height: '40px' }} />
                                    <h4 onClick={() => handleFollowerClick(follower)}>{follower?.login}</h4>
                                    <button style={{
                                        backgroundColor: isFollowingModal ? "#ccc" : "#007bff",
                                        color: isFollowingModal ? "#000" : "#fff"
                                    }}>
                                        {isFollowingModal ? "unfollow" : "follow"}
                                    </button>
                                </div>
                            )
                        ))}
                    </div>
                ) : (
                    <p>No {isFollowingModal ? "following" : "followers"} to show</p>
                )}
                <button className="close_followers_modal" onClick={onCloseModal}>
                    x
                </button>
            </div>
        </div>
    );

};

export const UserProfileDraw = connect((state) => ({ state: state }), {
    onProfile: actionPostById,
})(UserProfile);