import ContentEditable from 'react-contenteditable';
import icons from '../common/component/icons';
import React from 'react';
import PropTypes from 'prop-types';
import { showNotice } from '../common/utils';

const { __, sprintf } = wp.i18n;  // eslint-disable-line
const { createRef, Component, Fragment, RawHTML } = wp.element;
const { dispatch, select} = wp.data;

const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
export default class Comment extends React.Component {

    constructor(props) {

        super(props);
        this.contentEditable = React.createRef();
        this.edit = this.edit.bind(this);
        this.save = this.save.bind(this);
        this.remove = this.remove.bind(this);
        this.resolve = this.resolve.bind(this);
        this.copy = this.copy.bind(this);
        this.cancelEdit = this.cancelEdit.bind(this);
        this.state = { editing: false, showEditedDraft: false, contentHtml: '<br/>', editedTime: '', copySuccess: '' };
        this.val = props.value;

    }

    componentDidUpdate() {

        // Check if there are any elements matching the selector
        if (document.querySelectorAll('mdspan[data-rich-text-format-boundary="true"]').length !== 0) {
            const editedCommentID = this.props.timestamp;
            const textarea = document.getElementById(editedCommentID).querySelector('textarea');
    
            if (textarea) {
                const commentedText = textarea.value; // Get the current value
                textarea.focus(); // Focus the textarea
                textarea.value = ''; // Clear the textarea
                textarea.value = commentedText; // Set the value back to the commented text
            }
        }
    }

    edit() {
        this.setState({ editing: true });

        // Handling edited value.
        var editedValue = this.state.showEditedDraft ? this.props.editedDraft : this.props.children;

        editedValue = removeLinkFromEditableText(editedValue);
        this.state.contentHtml = editedValue;

        this.state.attachmentText = this.props.attachmentText;
        if ('' !== this.state.attachmentText) {
            this.setState({ mediaId: '', mediaName: '', mediaUrl: '' });
        }
    }

    save(event) {
        var elID = event.currentTarget.parentElement.parentElement.parentElement.parentElement.parentElement.id;
        let attachmentText;
        if (event.currentTarget.classList.contains('btn-disabled')) {
            return false;
        }
        if (document.querySelector(`#${elID} .js-cf-edit-comment`).textContent.trim().length !== 0) {
            var newText = this.state.contentHtml;
            if ('' === newText) {
                showNotice( __(
                    "Please add some comment.",
                    "commenting-feature"
                ));
                return false;
            }
            if (true === this.state.editing) {
                let editedTime = multicollabEditedTimezoneBlock ? multicollabEditedTimezoneBlock.editedTime : '';
                let editedTimeStamp = getTimestampWithTimezone();

                // code added by meet - removed state condition by pooja for edit attachment
                attachmentText = (('' !== this.state.attachmentText || 'undefined' !== this.state.attachmentText) || null === document.getElementById('cf_thumb_file')?.innerHTML) ? this.state.attachmentText : document.getElementById('cf_thumb_file')?.innerHTML;
                this.state.editedTime = editedTime;
                this.state.editedTimestamp = editedTimeStamp;
                if ('' === this.state.attachmentText || undefined === this.state.attachmentText) {
                    attachmentText = document.getElementById('cf_thumb_file')?.innerHTML;
                }

                if ('' !== this.props.assignedText && undefined !== this.props.assignedText && null !== this.props.assignedText) {
                    var assignedText = this.props.assignedText;
                    var span = document.createElement('span');
                    span.innerHTML = assignedText; //phpcs:ignore
                    span.classList.add('assigned-meta-text');
                    document.getElementById(this.props.timestamp).querySelector('.commentInnerContainer .commentText .readmoreTxt')?.after(span); //phpcs:ignore
                }
            }

            // Adding anchor tag around the linkable text.
            // For bug fixing of semicolon there is a little change in regex  
            newText = filterTextBeforeSave(newText);

            this.props.updateCommentFromBoard(newText, this.props.index, this.props.timestamp, this.props.dateTime, elID, this.state.editedTime, this.state.editedTimestamp, this.props.assignedText, attachmentText);

            this.setState({ editing: false });
        } else {
            showNotice( __(
                "Please add some comment.",
                "commenting-feature"
            ));
        }
    }

    remove(event) {
        const elID = event.currentTarget.closest('.cls-board-outer');
        this.props.removeCommentFromBoard(this.props.index, this.props.timestamp, elID.id);
        event.currentTarget.closest('.comment-delete-overlay').classList.remove("show");
    }
    copy(event) {
        // Stop event propagation to prevent buttons-wrapper toggle handler from interfering
        event.stopPropagation();
        event.preventDefault();
        
        const elID = event.currentTarget.closest('.cls-board-outer').id;
        const elIDRemove = elID;
        const current_url = window.location.href + '&current_url=' + elIDRemove; //phpcs:ignore
        const copyTextElement = document.querySelector('.copytext');
        if (copyTextElement) {
          copyTextElement.textContent = '';
        }
        const currebntCopyTextElement = document.getElementById(elIDRemove).querySelector('.copytext');
        if(currebntCopyTextElement){
            currebntCopyTextElement.textContent = current_url;
        }
        // hack for safari = add style='position: absolute; top: -8888px; left: -8888px'
        const tempInput = document.createElement("input");
        tempInput.setAttribute("style", "position: absolute; top: -8888px; left: -8888px");
        document.body.appendChild(tempInput);
        tempInput.setAttribute("value", current_url);
        tempInput.select();
        document.execCommand("copy");
        event.target.focus();
        tempInput.remove();
        
        // Close the more options menu - do it immediately and also after a delay
        const closeMenu = () => {
          // Try multiple approaches to find the buttons-wrapper
          let btnWrapper = null;
          
          // Method 1: From currentTarget (the <li> element)
          if(event.currentTarget){
            btnWrapper = event.currentTarget.closest('.buttons-wrapper');
          }
          
          // Method 2: From event target (might be child element like <i> or <span>)
          if(!btnWrapper){
            btnWrapper = event.target.closest('.buttons-wrapper');
          }
          
          // Method 3: Find from commentContainer
          if(!btnWrapper){
            const commentContainer = event.target.closest('.commentContainer') || event.currentTarget.closest('.commentContainer');
            if(commentContainer){
              btnWrapper = commentContainer.querySelector('.buttons-wrapper.active');
            }
          }
          
          // Close the found wrapper
          if(btnWrapper){
            btnWrapper.classList.remove('active');
            // Force a reflow to ensure the change is applied
            void btnWrapper.offsetHeight;
          }
          
          // Also close ALL open more options menus as a safety measure
          document.querySelectorAll('.buttons-wrapper.active').forEach(wrapper => {
            wrapper.classList.remove('active');
            void wrapper.offsetHeight;
          });
        };
        
        // Close immediately
        closeMenu();
        
        // Also close after a short delay to handle React re-renders
        setTimeout(closeMenu, 0);
        setTimeout(closeMenu, 10);
        setTimeout(closeMenu, 50);
        
        // Now update state
        this.setState({ copySuccess: __('Link Copied!', 'commenting-feature') });
        clearInterval(this.resetState());

        // Create an auxiliary hidden input
        const aux = document.createElement("input");
        aux.select();
    }
    resetState() {
        setTimeout(() => this.setState({ copySuccess: '' }), 3000);
    }

    resolve(event) {
        // Resolve comment become suggestion while resolve the comment.
        const iframe = cfGetIframe();
        const iframeDocument = iframe ? iframe.contentWindow.document : null;

        const elID = event.currentTarget.closest('.cls-board-outer').id;
        const elIDRemove = elID;

        const CurrentPostID = wp.data.select('core/editor').getCurrentPostId(); // eslint-disable-line
        const metaId = '_' + elID;

        const data = {
            action: 'multicollab_resolve_thread',
            currentPostID: CurrentPostID,
            metaId: metaId,
            nonce: multicollabActivityL10n.nonce
        };


        fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(data).toString(),
        })
        .then(data => {
            const threadsGlobalData = wp.data.select("mdstore").getAllCommentCount();
            if (threadsGlobalData?.length !== undefined) {
                const commentID = elID.replace('_', '');
                const newData = threadsGlobalData.find(c => c.elID === commentID);
            }
            const sidebarName = select("core/edit-post").getActiveGeneralSidebarName();
            if (sidebarName === "cf-activity-center/cf-activity-center") {
                dispatch("core/edit-post").closeGeneralSidebar("cf-activity-center/cf-activity-center");
            }
            // Add setTimeout to solve git issue: 470
            document.getElementById("cf-comment-board-wrapper")?.classList.remove("cf-unset-all");
            setTimeout(() => {
                const isel = document.getElementById(elIDRemove);
                if (isel) {
                    isel.remove();
                }
                document.querySelectorAll('#cf-comment-board-wrapper .cls-board-outer').forEach(el => {
                    el.classList.remove('focus');
                    el.removeAttribute('style');
                });
            }, 1000);

            let dataBlocks;
            let blockType;

            if(iframeDocument){
                dataBlocks = Array.from(iframeDocument.querySelectorAll(`[datatext="${elIDRemove}"]`)).map(el => el.getAttribute('data-block'));
                blockType = iframeDocument.querySelector(`[datatext="${elIDRemove}"]`)?.getAttribute('data-type');
            }else{
                dataBlocks = Array.from(document.querySelectorAll(`[datatext="${elIDRemove}"]`)).map(el => el.getAttribute('data-block'));
                blockType = document.querySelector(`[datatext="${elIDRemove}"]`)?.getAttribute('data-type');
            }
            

            // User can comment on whole block
            if (blockType !== undefined && dataBlocks && blockType !== null) {
                dataBlocks.forEach(clientId => {
                    dispatch('core/block-editor').updateBlockAttributes(clientId, { datatext: '' });
                });
            } else {
                // Remove Tag
                removeTag(elIDRemove); // eslint-disable-line
                document.getElementById(elIDRemove)?.remove();  
            }

            unsetBoardIdByValue(elIDRemove);


            wp.data.dispatch('mdstore').setIsActive(false);

            setTimeout(() => {
                const selectedNontextblock = wp.data.select('mdstore').getBoardIds();
                if( selectedNontextblock.length === 0 ) {
                    wp.data.dispatch('core/edit-post').closeGeneralSidebar('edit-post/cf-collab-sidebar');
                }
            }, 2000);
        })
        .catch(error => console.error('Error:', error));
    }

    cancelEdit() {
        this.state.attachmentText= this.props.attachmentText;
        this.setState({ editing: false })
    }
    deleteAttachment(event) {
        const elID = $(event.currentTarget).closest('.cls-board-outer');
        this.setState({ attachmentText: '', mediaId: '', mediaName: '', mediaUrl: '' })
        this.props.removeAttachmentFromBoard(this.props.index, this.props.timestamp, elID[0].id, this.props.attachmentText);
    }
    renderNormalMode() {
        // Display the textarea for new comments.
        const isShareCommentContainer = document.querySelector('.cls-board-outer.focus .shareCommentContainer');

        if (isShareCommentContainer) {
            isShareCommentContainer.style.display = 'block';
        }
        const { index } = this.props;
        const commentStatus = this.props.status ? this.props.status : 'publish';
        const attachment = this.props.attachmentText;

        // convert time to timeAgo format

        let dateTime = timeAgo(this.props.timestamp);
        let convertedDate = convertedDatetime(this.props.timestamp);

        let owner = '';
        try {
            owner = wp.data.select("core").getCurrentUser().id; // eslint-disable-line
        } catch (e) {
            owner = localStorage.getItem("userID");
        }

        let str = this.state.showEditedDraft ? this.props.editedDraft : this.props.children;
        // Ensure that str is a string
        str = typeof str === 'string' ? str : '';
        let readmoreStr = '';
        const maxLength = 300;
        if (maxLength < str.replace(/<\/?[^>]+(>|$)/g, "").length) {
            readmoreStr = str;
            str = str.substring(0, maxLength) + '...';
        }
        // Removing contenteditable attr from the link.
        str = str.replace(/contenteditable=\"false\"/ig, 'data-edit="false"'); // eslint-disable-line

        // Limiting User Role Character.
        var userRolePartial = this.props.userRole;
        if (8 < userRolePartial.length) {
            userRolePartial = userRolePartial.slice(0, 8) + '...';
        }

        const isShowAllCommentClicked = document.querySelector('.cls-board-outer.focus .show-all-comments');
        let displayValue = 'block';

        if (this.props.index > getCommentsLimit()) {
            displayValue = 'none';
        }

        if( 'block' !== isShowAllCommentClicked?.style.display && undefined !== isShowAllCommentClicked?.style.display ) {
            displayValue = 'block';
        }

        if('' === attachment){
            this.state.attachmentText = '';
        }

        const readlessHtml = `
        <span class='readlessTxt readMoreSpan active'>
            ${str}
            ${'' !== readmoreStr ? `<span class='readmoreComment'>${__('show more', 'commenting-feature')}</span>` : ''}
        </span>
    `;

    const readmoreHtml = `
        <span class='readmoreTxt readMoreSpan'>
            ${readmoreStr}
            ${'' !== readmoreStr ? `<span class='readlessComment'>${__('show less', 'commenting-feature')}</span>` : ''}
        </span>
    `;

    let avatarProfileURL;
    if (this.state.currentUserid !== this.props.userID) {
        avatarProfileURL = this.props.profileURL || '';
    } else {
        avatarProfileURL = localStorage.getItem("userURL") || ''; 
    }
    
        return (
            <div className={"commentContainer"} style={{ display: displayValue }} id={this.props.timestamp}>
                <div className="commentInnerContainer">
                    <div className="comment-header">
                        <div className="comment-details">
                            {"1" === this.props.showAvatars &&
                                <div className="avatar">
                                    <img src={avatarProfileURL} alt="avatar" />
                                </div>
                            }
                            <div className="commenter-name-time">
                                <div className="commenter-name">
                                {this.props.userName.charAt(0).toUpperCase() +
                                this.props.userName.slice(1)}
                                    <span className="tooltip">{this.props.userRole}</span>
                                </div>

                                <div className="comment-time"><span className="comment-time-wrapper">{dateTime} <span className="tooltip">{convertedDate} </span></span>
                                </div>
                            </div>
                            <div className="comment-actions">
                                        <Fragment>
                                            {index === 0 && "guest" !== multicollabCurrentUserInfo.role &&
                                                <div className="comment-resolve">
                                                    <input id={"resolve_cb_" + this.props.timestamp + '_' + index} type="checkbox" className="resolve-cb" value="1" />
                                                    <label htmlFor={"resolve_cb_" + this.props.timestamp + '_' + index}>{__('Resolved', 'commenting-feature')}</label>
                                                    <span className="tooltip">{__('Mark as Resolved', 'commenting-feature')}</span>
                                                </div>
                                            }
                                        </Fragment>
                                    
                                
                                {index === 0 &&
                                    (

                                        <Fragment>
                                            {'' !== this.state.copySuccess &&
                                                <p className="comment-copied-tooltip">{this.state.copySuccess}</p>
                                            }
                                            <div className="buttons-wrapper">

                                                <span className="tooltip">{__('More Options...', 'commenting-feature')}</span>
                                                <div className="more-option-btn">
                                                    <div className="cf-option-light-btn">{icons.moreFirstOption}</div>
                                                    <div className="cf-option-midlight-btn">{icons.moreSecndOption}</div>
                                                    <div className="cf-option-dark-btn">{icons.moreThirdOption}</div>
                                                    </div>
                                                <div className="comment-more-option">
                                                    <ul className="comment-more-option-list">
                                                        <li onClick={this.copy.bind(this)}>
                                                            <i className="dashicons dashicons-share" title={__('Copy Link', 'commenting-feature')}></i><span className="more-option-meta">{__('Share', 'commenting-feature')}</span>
                                                        </li>
                                                        {this.props.userID === owner &&
                                                            <Fragment>
                    
                                                                
                                                                    

                                                                        <li onClick={this.edit} className="js-edit-comment">
                                                                            <i className="dashicons dashicons-edit" title="Edit"></i><span className="more-option-meta">{__('Edit', 'commenting-feature')}</span>
                                                                        </li>
                                                                        <li className="js-resolve-comment">
                                                                            <i className="dashicons dashicons-trash" title="Resolve"></i><span className="more-option-meta">{__('Delete', 'commenting-feature')}</span>
                                                                        </li>

                                                                    
                                                                

                                                            </Fragment>

                                                        }
                                                    </ul></div></div>
                                        </Fragment>

                                    )
                                }
                                {this.props.userID === owner && index > 0 &&
                                                            
                                            <Fragment>
                                                <div className="buttons-wrapper">
                                                    <span className="tooltip">{__('More Options...', 'commenting-feature')}</span>
                                                    <div className="more-option-btn">
                                                        <div className="cf-option-light-btn">{icons.moreFirstOption}</div>
                                                        <div className="cf-option-midlight-btn">{icons.moreSecndOption}</div>
                                                        <div className="cf-option-dark-btn">{icons.moreThirdOption}</div>
                                                    </div>
                                                    <div className="comment-more-option">
                                                        <ul className="comment-more-option-list">

                                                            <li onClick={this.edit}>
                                                                <i className="dashicons dashicons-edit js-edit-comment" title="Edit"></i><span className="more-option-meta">{__('Edit', 'commenting-feature')}</span>
                                                            </li>
                                                            <li className="js-trash-comment">
                                                                <i className="dashicons dashicons-trash" title="Delete"></i><span className="more-option-meta">{__('Delete', 'commenting-feature')}</span>
                                                            </li>
                                                        </ul></div></div>
                                            </Fragment>
                                }

                            </div>
                        </div>
                    </div>
                    <div className="commentText">
                    <RawHTML>{readlessHtml}{readmoreHtml}</RawHTML>
                        {'' !== this.props.assignedText && undefined !== this.props.assignedText &&
                            <span className="assigned-meta-text">{this.props.assignedText}</span>
                        }
                        
                    </div>
                    <div className="comment-delete-overlay">
                        <span className="comment-overlay-text">{index === 0 ? __('Delete this comment thread?', 'commenting-feature') : __('Delete this comment?', 'commenting-feature')}</span>
                        <div className="comment-delete-overlay-inner">
                            <button onClick={index === 0 ? this.resolve.bind(this) : this.remove.bind(this)} className="btn btn-delete"> {__('Delete', 'commenting-feature')}</button>
                            <button onClick={this.cancelEdit.bind(this)} className="btn btn-cancel">{__('Cancel', 'commenting-feature')}</button>
                        </div>
                    </div>
                    {'' !== this.props.editedTimestamp && undefined !== this.props.editedTimestamp &&
                        <time className="updated-time">{sprintf(__('edited at %s', 'commenting-feature'), timeAgo(this.props.editedTimestamp))}<span className="tooltip">{convertedDatetime(this.props.editedTimestamp.toString())}</span></time>
                    }
                    {'' === this.props.editedTimestamp && '' !== this.props.editedTime && undefined !== this.props.editedTime &&
                        <time className="updated-time">{sprintf(__('edited at %s', 'commenting-feature'), this.props.editedTime)}<span className="tooltip">{this.props.editedTime}</span></time>
                    }
                </div>
            </div>
        );
    }

    renderEditingMode() {
        var previousValue = this.props.children;

        var previousAttachment = this.props.attachmentText;
        // Hide the textarea for new comments.
        const isShareCommentContainer = document.querySelector('.cls-board-outer.focus .shareCommentContainer');
        if (isShareCommentContainer) {
            isShareCommentContainer.style.display = 'none';
        }

        // Limiting User Role Character.
        var userRolePartial = this.props.userRole;
        if (8 < userRolePartial.length) {
            userRolePartial = userRolePartial.slice(0, 8) + '...';
        }
        // convert time to timeAgo format 
        let dateTime = timeAgo(this.props.timestamp);
        let convertedDate = this.props.dateTime;

        previousValue = removeLinkFromEditableText(previousValue);
        previousValue = filterTextForEdit(previousValue);
        var newText = this.state.contentHtml;
        newText = filterTextForEdit(newText);
        
        var newAttchment = this.state.attachmentText;
        let buttonClass = '';
        if (newText === '' || (newText === previousValue && newAttchment === previousAttachment)) {
            buttonClass = 'btn-disabled';
        }
        return (
            <div className="commentContainer commentEdit" id={this.props.timestamp}>
                <div className="commentInnerContainer">
                    <div className="comment-header">
                        <div className="comment-details">
                            <div className="avatar"><img src={this.props.profileURL} alt="avatar" /></div>
                            <div className="commenter-name-time">
                                <div className="commenter-name">
                                {this.props.userName.charAt(0).toUpperCase() +
                                this.props.userName.slice(1)}
                                    <span className="tooltip">{this.props.userRole}</span>
                                </div>
                                <div className="comment-time">{dateTime} <span className="tooltip">{convertedDate} </span> </div>
                            </div>
                        </div>
                    </div>
                    <div className="commentText">
                        <div className="cf-share-comment-wrapper js-cf-share-comment-wrapper">
                            <ContentEditable
                                innerRef={this.contentEditable}
                                html={this.state.contentHtml}
                                disabled={false}
                                onChange={(e) => this.setState({ contentHtml: e.target.value })}
                                id={`edit-${this.props.timestamp}`}
                                className="cf-share-comment js-cf-edit-comment"
                                placeholder={__('Edit your comments...', 'commenting-feature')}

                            />
                        </div>

                        {'' !== this.props.assignedText && undefined !== this.props.assignedText &&
                            <span className="assigned-meta-text">{this.props.assignedText}</span>
                        }
                    </div>
                    <button onClick={this.save.bind(this)} className={`btn-comment save-btn ${buttonClass}`}>
                        {__('Save', 'commenting-feature')}
                        <span className="tooltip">{__('Save Changes', 'commenting-feature')}</span>
                    </button>
                    <button onClick={this.cancelEdit.bind(this)} className="btn-comment js-cancel-comment">
                        {__('Cancel', 'commenting-feature')}
                        <span className="tooltip">{__('Discard Changes', 'commenting-feature')}</span>
                    </button>
                </div>
            </div>
        );
    }

    render() {
        if (this.state.editing) {
            return this.renderEditingMode();
        } else {
            return this.renderNormalMode();
        }
    }
}

// Typecheck.
Comment.propTypes = {
    index: PropTypes.number,
    removeCommentFromBoard: PropTypes.func,
    updateCommentFromBoard: PropTypes.func,
    removeAttachmentFromBoard: PropTypes.func,
    userName: PropTypes.string,
    userRole: PropTypes.string,
    dateTime: PropTypes.string,
    profileURL: PropTypes.string,
    showAvatars: PropTypes.string,
    userID: PropTypes.number,
    status: PropTypes.string,
    lastVal: PropTypes.object,
    onChanged: PropTypes.func,
    selectedText: PropTypes.string,
    timestamp: PropTypes.number,
    editedDraft: PropTypes.string,
    children: PropTypes.string,
    editedTime: PropTypes.string,
    editedTimestamp: PropTypes.string,
    blockType: PropTypes.string,
    assignedText: PropTypes.string,
    attachmentText: PropTypes.string,
};
