// import React, { useEffect, useState } from "react";
// import { Button, Box } from "@mui/material";
// import { useStore } from "react-redux";
// import { StyledComment, Avatar, BoxWrapper } from "./comment.module";
// import {
//     gqlAddLikeComment,
//     gqlDeleteLikeComment,
// } from "../../actions/likeInComment";
// import { actionAnswerComment } from "../../actions";
//
// const Comments = ({
//                       comments,
//                       isShowExtendedComments,
//                       setIsShowExtendedComments,
//                       currentUser
//                   }) => {
//     const userId = useStore().getState().auth.payload.id;
//     const user = {
//         login: currentUser?.login,
//         url: currentUser?.avatar?.url
//     };
//
//     const [stateComments, setComments] = useState(comments);
//     const [showAnswerInput, setShowInputAnsw] = useState(false);
//     const [answComm, setanswComm] = useState('');
//     const [showAnswerState, setshowAnswerState] = useState(false);
//     const [answerCommId, setIdcomm] = useState(null);
//
//     useEffect(() => {
//         setComments(comments);
//     }, [comments]);
//
//     const showAnswerInpt = (id) => {
//         setIdcomm(id);
//         setShowInputAnsw((prevValue) => !prevValue);
//     };
//
//     const updtanswcomm = (e) => {
//         setanswComm(e.target.value);
//     };
//
//     const answCommPost = () => {
//         setShowInputAnsw(false);
//         setshowAnswerState(true);
//         actionAnswerComment(answerCommId, answComm, user);
//     };
//
//     const handleLikeComment = async (commentId) => {
//         try {
//             await gqlAddLikeComment(commentId);
//             const updatedComments = stateComments.map((comment) => {
//                 if (comment._id === commentId) {
//                     return {
//                         ...comment,
//                         likes: [
//                             ...comment.likes,
//                             { owner: { _id: userId } },
//                         ],
//                     };
//                 } else {
//                     return comment;
//                 }
//             });
//             setComments(updatedComments);
//         } catch (error) {
//             console.error(error);
//         }
//     };
//
//     const handleUnlikeComment = async (commentId) => {
//         const comment = stateComments.find((c) => c._id === commentId);
//         const like = comment?.likes?.find((l) => l.owner._id === userId);
//         if (!like) {
//             return;
//         }
//         try {
//             await gqlDeleteLikeComment(like._id, commentId);
//             const updatedLikes = comment.likes.filter((l) => l.owner._id !== userId);
//             const updatedComments = stateComments.map((c) => {
//                 if (c._id === commentId) {
//                     return { ...c, likes: updatedLikes };
//                 } else {
//                     return c;
//                 }
//             });
//             setComments(updatedComments);
//         } catch (error) {
//             console.error(error);
//         }
//     };
//
//     return (
//         <Box style={{height:'100px'}}>
//             <BoxWrapper
//                 style={{
//                     maxHeight: isShowExtendedComments ? "100%" : "100px",
//                 }}
//             >
//                 {stateComments?.slice(0, 2).map((comment) => (
//                     <div>
//                         <StyledComment key={comment._id}>
//
//                             <Avatar
//                                 style={{ height: '40px', width: '40px' }}
//                                 src={
//                                     comment.owner?.avatar?.url
//                                         ? comment.owner?.avatar?.url
//                                         : "https://w7.placeholder.com/40"
//                                 }
//                                 alt="Avatar"
//                             />
//
//
//                             <div style={{ display: 'flex', flexDirection: 'column' }}>
//
//                                 <div>
//                                     {comment && (
//                                         <span onClick={() => showAnswerInpt(comment._id)}> {comment.text} </span>
//                                     )}
//                                 </div>
//
//                                 <div style={{display:'flex'}}>
//                                     <p style={{ fontSize: '10px', color: 'grey' }}>
//                                         Likes {comment.likes?.length}
//                                     </p>
//                                     <div style={{ fontSize: '10px', color: 'grey', marginLeft:'15px' }} onClick={() => showAnswerInpt(comment._id)}>
//                                         Answer
//                                     </div>
//                                     {showAnswerInput && answerCommId === comment._id && (
//                                         <div style={{marginLeft:'15px'}}>
//                                             <input type="text" value={answComm} onChange={updtanswcomm} />
//                                             <button onClick={answCommPost}>Send</button>
//                                         </div>
//                                     )}
//                                     {showAnswerState && (
//                                         <div style={{marginLeft:'15px'}}>
//                                             <p>Answer send!</p>
//                                         </div>
//                                     )}
//                                 </div>
//                             </div>
//
//
//
//
//
//                             <div style={{ marginLeft: 'auto' }}>
//                             <div>
//                                 {comment.likes.some((like) => like.owner._id === userId) ? (
//                                     <Button onClick={() => handleUnlikeComment(comment._id)}>
//                                         <svg style={{ width: '15px', height: '15px' }} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#838383"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M12.39 20.87a.696.696 0 0 1-.78 0C9.764 19.637 2 14.15 2 8.973c0-6.68 7.85-7.75 10-3.25 2.15-4.5 10-3.43 10 3.25 0 5.178-7.764 10.664-9.61 11.895z"fill="#828282"></path></g>
//                                         </svg>
//                                     </Button>
//                                 ) : (
//                                     <Button onClick={() => handleLikeComment(comment._id)}>
//                                         <svg style={{ width: '15px', height: '15px' }} fill="#000000" height="200px" width="200px" version="1.1" id="Capa_1" viewBox="0 0 471.701 471.701" stroke="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><g><path d="M433.601,67.001c-24.7-24.7-57.4-38.2-92.3-38.2s-67.7,13.6-92.4,38.3l-12.9,12.9l-13.1-13.1 c-24.7-24.7-57.6-38.4-92.5-38.4c-34.8,0-67.6,13.6-92.2,38.2c-24.7,24.7-38.3,57.5-38.2,92.4c0,34.9,13.7,67.6,38.4,92.3 l187.8,187.8c2.6,2.6,6.1,4,9.5,4c3.4,0,6.9-1.3,9.5-3.9l188.2-187.5c24.7-24.7,38.3-57.5,38.3-92.4 C471.801,124.501,458.301,91.701,433.601,67.001z M414.401,232.701l-178.7,178l-178.3-178.3c-19.6-19.6-30.4-45.6-30.4-73.3 s10.7-53.7,30.3-73.2c19.5-19.5,45.5-30.3,73.1-30.3c27.7,0,53.8,10.8,73.4,30.4l22.6,22.6c5.3,5.3,13.8,5.3,19.1,0l22.4-22.4 c19.6-19.6,45.7-30.4,73.3-30.4c27.6,0,53.6,10.8,73.2,30.3c19.6,19.6,30.3,45.6,30.3,73.3 C444.801,187.101,434.001,213.101,414.401,232.701z"></path></g></g>
//                                         </svg>
//                                     </Button>
//                                 )}
//                             </div>
//                         </div>
//
//
//
//
//                         </StyledComment>
//                     </div>
//                 ))}
//             </BoxWrapper>
//
//             <div style={{ display: "flex", justifyContent: "center" }}>
//                 {(stateComments.length > 2 || (stateComments.length === 2 && !isShowExtendedComments)) && (
//                     <Button onClick={() => setIsShowExtendedComments((prevValue) => !prevValue)}>
//                         {isShowExtendedComments ? "Show less" : "Show more"}
//                     </Button>
//                 )}
//             </div>
//
//
//         </Box>
//     );
// };
//
// export default Comments;


import React, {useEffect, useState,} from "react";
import { CommentWrapper, IconComment, CommentBox, StyledButton } from "../PostDraw/post-draw.module";
import {Button, Box} from "@mui/material";
import {useStore} from "react-redux";
import {StyledComment, Avatar, BoxWrapper} from "./comment.module";
import {
    gqlAddLikeComment,
    gqlDeleteLikeComment,
} from "../../actions/likeInComment";
import {actionAnswerComment, actionSendComment} from "../../actions";

const Comments = ({
                      isShowExtendedComments,
                      setIsShowExtendedComments,
                      currentUser,
                      post
                  }) => {

    const userId = useStore().getState().auth.payload.id;
    const user = {
        login: currentUser?.login,
        url: currentUser?.avatar?.url
    }

    const [stateComments, setComments] = useState(post.comments ?? []);
    const [showAnswerInput, setShowInputAnsw] = useState(false);
    const [answComm, setanswComm] = useState('')
    const [showAnswerState, setshowAnswerState] = useState(false)
    const [answerCommId, setIdcomm] = useState(null)




    const showAnswerInpt = (id) => {
        setIdcomm(id)
        setShowInputAnsw(prevValue => !prevValue);
    }

    const updtanswcomm = (e) => {
        setanswComm(e.target.value)
    }

    const answCommPost = () => {
        setShowInputAnsw(false)
        setshowAnswerState(true)
        actionAnswerComment(answerCommId, answComm, user)
    }

    const handleLikeComment = async (commentId) => {
        try {
            await gqlAddLikeComment(commentId);
            const updatedComments = stateComments.map((comment) => {
                if (comment._id === commentId) {
                    return {
                        ...comment,
                        likes: [
                            ...comment.likes,
                            {owner: {_id: userId}},
                        ],
                    };
                } else {
                    return comment;
                }
            });
            setComments(updatedComments);
        } catch (error) {
            console.error(error);
        }
    };

    const handleUnlikeComment = async (commentId) => {
        const comment = stateComments.find((c) => c._id === commentId);
        const like = comment?.likes?.find((l) => l.owner._id === userId);
        if (!like) {
            return;
        }
        try {
            await gqlDeleteLikeComment(like._id, commentId);
            const updatedLikes = comment.likes.filter(
                (l) => l.owner._id !== userId
            );
            const updatedComments = stateComments.map((c) => {
                if (c._id === commentId) {
                    return {...c, likes: updatedLikes};
                } else {
                    return c;
                }
            });
            setComments(updatedComments);
        } catch (error) {
            console.error(error);
        }
    };


    const [newCommnet,setComment] = useState('')


    const clickCommentHandler = async (event, postId) => {
        try {
            actionSendComment(postId, newCommnet)
        } catch (e) {
            console.error(e)
        }
        finally {
            setComment('')
        }
    };

    const handlePostComment = (event, postId) => {
        if (newCommnet?.length === 0) {
            alert("Please enter a comment")
        }
        else {
            const addStateComment = {
                _id: Math.random(),
                text: newCommnet,
                owner: { avatar: { url: currentUser?.avatar?.url } },
            };
            setComments((prevComments) => [...prevComments, addStateComment]);
            return clickCommentHandler(event, postId)
        }
    };

    return (
        <Box>
            <BoxWrapper
                style={{
                    maxHeight: isShowExtendedComments ? "100%" : "100px",
                }}
            >
                {stateComments?.slice(0, 2).map((comment) => (
                    <div>

                        <StyledComment key={comment._id}>
                            <Avatar
                                style={{height: '40px', width: '40px'}}
                                src={
                                    comment.owner?.avatar?.url
                                        ? comment.owner?.avatar?.url
                                        : "https://w7.pngwing.com/pngs/336/946/png-transparent-avatar-user-medicine-surgery-patient-avatar-face-heroes-head.png"
                                }
                            />

                            <div style={{display: 'flex', flexDirection: 'column'}}>
                                <div>
                                    {comment && <span onClick={() => showAnswerInpt(comment._id)}>{comment.text}</span>}
                                </div>
                                <div style={{display: 'flex'}}>
                                    <p style={{fontSize: '10px', color: 'grey'}}>Likes {comment?.likes?.length}</p>
                                    <div style={{ fontSize: '10px', color: 'grey', marginLeft:'15px' }} onClick={() => showAnswerInpt(comment._id)}>
                                        Answer
                                    </div>
                                    {showAnswerInput && answerCommId === comment._id && (
                                        <div style={{marginLeft:'15px'}}>
                                            <input type="text" value={answComm} onChange={updtanswcomm} /><button onClick={answCommPost}>Send</button>
                                        </div>
                                    )}
                                    {showAnswerState && (
                                        <div style={{marginLeft:'15px'}}>
                                            <p>Answer send!</p>
                                        </div>
                                    )}
                                </div>

                            </div>

                            <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'flex-end', marginLeft: 'auto'}}>
                                <Button
                                    onClick={() => {
                                        if (comment?.likes?.some((like) => like.owner._id === userId)) {
                                            handleUnlikeComment(comment._id);
                                        } else {
                                            handleLikeComment(comment._id);
                                        }
                                    }}
                                >
                                    {comment?.likes?.some((like) => like.owner._id === userId)
                                        ? <svg style={{width:"15px", height:'15px'}} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#838383"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M12.39 20.87a.696.696 0 0 1-.78 0C9.764 19.637 2 14.15 2 8.973c0-6.68 7.85-7.75 10-3.25 2.15-4.5 10-3.43 10 3.25 0 5.178-7.764 10.664-9.61 11.895z" fill="#828282"></path></g></svg>
                                        :  <svg style={{width:"15px", height:'15px'}} fill="#000000" height="200px" width="200px" version="1.1" id="Capa_1" viewBox="0 0 471.701 471.701" stroke="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M433.601,67.001c-24.7-24.7-57.4-38.2-92.3-38.2s-67.7,13.6-92.4,38.3l-12.9,12.9l-13.1-13.1 c-24.7-24.7-57.6-38.4-92.5-38.4c-34.8,0-67.6,13.6-92.2,38.2c-24.7,24.7-38.3,57.5-38.2,92.4c0,34.9,13.7,67.6,38.4,92.3 l187.8,187.8c2.6,2.6,6.1,4,9.5,4c3.4,0,6.9-1.3,9.5-3.9l188.2-187.5c24.7-24.7,38.3-57.5,38.3-92.4 C471.801,124.501,458.301,91.701,433.601,67.001z M414.401,232.701l-178.7,178l-178.3-178.3c-19.6-19.6-30.4-45.6-30.4-73.3 s10.7-53.7,30.3-73.2c19.5-19.5,45.5-30.3,73.1-30.3c27.7,0,53.8,10.8,73.4,30.4l22.6,22.6c5.3,5.3,13.8,5.3,19.1,0l22.4-22.4 c19.6-19.6,45.7-30.4,73.3-30.4c27.6,0,53.6,10.8,73.2,30.3c19.6,19.6,30.3,45.6,30.3,73.3 C444.801,187.101,434.001,213.101,414.401,232.701z"></path> </g> </g></svg>
                                    }
                                </Button>
                            </div>

                        </StyledComment>

                        {/*{showAnswerInput &&*/}
                        {/*    <div className="answerTo_block"><span style={{color: '#1976d2'}}>Answer</span>*/}
                        {/*        <input value={answComm} onChange={updtanswcomm} placeholder="comment"/>*/}
                        {/*        <Button onClick={() => answCommPost()}>Post</Button>*/}
                        {/*    </div>*/}
                        {/*}*/}

                        {
                            comment?.answerTo &&
                            <div className="answerTo_block">
                                <span style={{color: '#1976d2'}}></span>
                                <Avatar
                                src={
                                    comment.owner?.avatar?.url
                                        ? comment.answerTo.owner?.avatar?.url
                                        : "https://w7.pngwing.com/pngs/336/946/png-transparent-avatar-user-medicine-surgery-patient-avatar-face-heroes-head.png"
                                } />
                                <span>{comment.answerTo.text}</span></div>
                        }
                    </div>
                ))}
                {stateComments?.slice(2).map((comment) => (
                    <StyledComment
                        key={comment._id}
                        style={{
                            opacity: isShowExtendedComments ? 1 : 0,
                            height: isShowExtendedComments ? "auto" : 0,
                        }}
                    >
                        <Avatar src={comment.owner?.avatar?.url}/>

                        <div style={{display: 'flex', flexDirection: 'column'}}>
                            <div>
                                {comment && <span onClick={() => showAnswerInpt(comment._id)}>{comment.text}</span>}
                            </div>
                            <div style={{display: 'flex'}}>
                                <p style={{fontSize: '10px', color: 'grey'}}>Likes {comment.likes?.length}</p>
                                <div style={{ fontSize: '10px', color: 'grey', marginLeft:'15px' }} onClick={() => showAnswerInpt(comment._id)}>
                                    Answer
                                </div>
                                {showAnswerInput && answerCommId === comment._id && (
                                    <div style={{marginLeft:'15px'}}>
                                        <input type="text" value={answComm} onChange={updtanswcomm} /><button onClick={answCommPost}>Send</button>
                                    </div>
                                )}
                                {showAnswerState && (
                                    <div style={{marginLeft:'15px'}}>
                                        <p>Answer send!</p>
                                    </div>
                                )}
                            </div>
                        </div>

                        <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'flex-end', marginLeft: 'auto'}}>
                            <Button
                                onClick={() => {
                                    if (comment?.likes?.some((like) => like.owner._id === userId)) {

                                        handleUnlikeComment(comment._id);
                                    } else {
                                        handleLikeComment(comment._id);
                                    }
                                }}
                            >
                                {comment?.likes?.some((like) => like.owner._id === userId)
                                    ? <svg style={{width:"15px", height:'15px'}}viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#838383"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M12.39 20.87a.696.696 0 0 1-.78 0C9.764 19.637 2 14.15 2 8.973c0-6.68 7.85-7.75 10-3.25 2.15-4.5 10-3.43 10 3.25 0 5.178-7.764 10.664-9.61 11.895z" fill="#828282"></path></g></svg>
                                    :  <svg style={{width:"15px", height:'15px'}} fill="#000000" height="200px" width="200px" version="1.1" id="Capa_1" viewBox="0 0 471.701 471.701" stroke="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M433.601,67.001c-24.7-24.7-57.4-38.2-92.3-38.2s-67.7,13.6-92.4,38.3l-12.9,12.9l-13.1-13.1 c-24.7-24.7-57.6-38.4-92.5-38.4c-34.8,0-67.6,13.6-92.2,38.2c-24.7,24.7-38.3,57.5-38.2,92.4c0,34.9,13.7,67.6,38.4,92.3 l187.8,187.8c2.6,2.6,6.1,4,9.5,4c3.4,0,6.9-1.3,9.5-3.9l188.2-187.5c24.7-24.7,38.3-57.5,38.3-92.4 C471.801,124.501,458.301,91.701,433.601,67.001z M414.401,232.701l-178.7,178l-178.3-178.3c-19.6-19.6-30.4-45.6-30.4-73.3 s10.7-53.7,30.3-73.2c19.5-19.5,45.5-30.3,73.1-30.3c27.7,0,53.8,10.8,73.4,30.4l22.6,22.6c5.3,5.3,13.8,5.3,19.1,0l22.4-22.4 c19.6-19.6,45.7-30.4,73.3-30.4c27.6,0,53.6,10.8,73.2,30.3c19.6,19.6,30.3,45.6,30.3,73.3 C444.801,187.101,434.001,213.101,414.401,232.701z"></path> </g> </g></svg>
                                }
                            </Button>
                        </div>
                    </StyledComment>
                ))}
            </BoxWrapper>
            <div style={{ display: "flex", justifyContent: "center" }}>
                {(stateComments.length > 2 || (stateComments.length === 2 && !isShowExtendedComments)) && (
                    <Button onClick={() => setIsShowExtendedComments((prevValue) => !prevValue)}>
                        {isShowExtendedComments ? "Скрыть комментарии" : "Показать комментарии"}
                    </Button>
                )}
            </div>
            <CommentWrapper className="comment-wrapper">
                <IconComment src="https://cdn-icons-png.flaticon.com/512/747/747402.png" />
                <CommentBox
                    placeholder="Add a comment"
                    value={newCommnet}
                    onChange={(event) => setComment(event.target.value)}
                    inputProps={{ style: { backgroundColor: "transparent" } }}
                />
                <StyledButton onClick={(event) => handlePostComment(event, post._id)}>
                    post
                </StyledButton>
            </CommentWrapper>
        </Box>
    );
};

export default Comments


