// User Comments Edit Component
// Displays and configures user comments with various display options

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    TextControl,
    ToggleControl
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import MultiSelect from '../../components/MultiSelect';
import { Fragment, useState, useEffect } from '@wordpress/element';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        postType,
        commentsPerPage,
        profileUserRoles,
        viewerRoles,
        showPagination
    } = attributes;

    const [comments, setComments] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState('');

    // Get user data from context prop (Query Loop style)
    	const user = context?.['wpuf-ud/userObject'] || {
        id: 0,
        display_name: __('Sample User', 'wpuf-pro'),
        user_login: 'sampleuser',
        user_email: 'sample@example.com'
    };

    const blockProps = useBlockProps();

    // Get post types from localized data
    const postTypes = window.wpufUserDirectory?.postTypes || [
        { label: __('Posts', 'wpuf-pro'), value: 'post' },
        { label: __('Pages', 'wpuf-pro'), value: 'page' }
    ];

    // Roles options: convert wp-localized userRoles (array of {value,label}) to key=>label map, with fallback
    const roleOptionsBase = (() => {
        const dynamicRoles = window.wpufUserDirectory?.userRoles || [];
        if (Array.isArray(dynamicRoles) && dynamicRoles.length > 0) {
            return dynamicRoles.reduce((acc, role) => {
                if (role && role.value) {
                    acc[role.value] = role.label || role.value;
                }
                return acc;
            }, {});
        }
        return {
            all: __('All Roles', 'wpuf-pro'),
            administrator: __('Administrator', 'wpuf-pro'),
            editor: __('Editor', 'wpuf-pro'),
            author: __('Author', 'wpuf-pro'),
            contributor: __('Contributor', 'wpuf-pro'),
            subscriber: __('Subscriber', 'wpuf-pro'),
        };
    })();

    // Extend roles with special Guest option for viewer rules
    const roleOptions = {
        ...roleOptionsBase,
        guest: __('Guest', 'wpuf-pro'),
    };

    // Fetch real comments for the user
    useEffect(() => {
        const fetchComments = async () => {
            if (!user.id || user.id === 0) {
                // Show sample data for preview when no real user
                setComments([
                    {
                        id: 1,
                        content: __('This is a sample comment that demonstrates how the user comments block will display content.', 'wpuf-pro'),
                        date: '2024-01-15T10:00:00',
                        post_title: __('Sample Post Title 1', 'wpuf-pro'),
                        post_id: 1,
                        reply_count: 2
                    },
                    {
                        id: 2,
                        content: __('Another sample comment to show how multiple comments would appear in the user comments block.', 'wpuf-pro'),
                        date: '2024-01-10T14:30:00',
                        post_title: __('Sample Post Title 2', 'wpuf-pro'),
                        post_id: 2,
                        reply_count: 0
                    }
                ]);
                setIsLoading(false);
                return;
            }

            setIsLoading(true);
            setError('');

            try {
                // Use wp.apiFetch for authenticated requests in the editor
                const data = await wp.apiFetch({
                    path: `/wp/v2/comments?author=${user.id}&per_page=${commentsPerPage}&orderby=date&order=desc&_embed&status=approve`
                });

                if (Array.isArray(data)) {
                    // Filter comments by post type if specified
                    let filteredComments = data;
                    if (postType && postType !== 'all') {
                        filteredComments = data.filter(comment => {
                            const post = comment._embedded?.up?.[0];
                            return post && post.type === postType;
                        });
                    }
                    setComments(filteredComments);
                } else {
                    setComments([]);
                }
            } catch (err) {
                console.error('Error fetching comments:', err);
                setError(__('Failed to load comments', 'wpuf-pro'));
                // Fallback to sample data on error
                setComments([
                    {
                        id: 1,
                        content: __('This is a sample comment that demonstrates how the user comments block will display content.', 'wpuf-pro'),
                        date: '2024-01-15T10:00:00',
                        post_title: __('Sample Post Title 1', 'wpuf-pro'),
                        post_id: 1,
                        reply_count: 2
                    },
                    {
                        id: 2,
                        content: __('Another sample comment to show how multiple comments would appear in the user comments block.', 'wpuf-pro'),
                        date: '2024-01-10T14:30:00',
                        post_title: __('Sample Post Title 2', 'wpuf-pro'),
                        post_id: 2,
                        reply_count: 0
                    }
                ]);
            } finally {
                setIsLoading(false);
            }
        };

        fetchComments();
    }, [user.id, postType, commentsPerPage]);

    // Restrict by selected profile roles (editor preview)
    const selectedRoles = Array.isArray(profileUserRoles) && profileUserRoles.length ? profileUserRoles : ['all'];
    const userRoles = Array.isArray(user?.roles) ? user.roles : [];
    const roleAllowed = selectedRoles.includes('all') || userRoles.some((r) => selectedRoles.includes(r));
    // Viewer roles are enforced on frontend; allow in preview to avoid confusion
    const selectedViewerRoles = Array.isArray(viewerRoles) && viewerRoles.length ? viewerRoles : ['all'];
    const viewerAllowed = true;

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Comments Settings', 'wpuf-pro')} initialOpen={true}>
                    <SelectControl
                        label={__('Post Type', 'wpuf-pro')}
                        value={postType}
                        options={[
                            { label: __('All Types', 'wpuf-pro'), value: 'all' },
                            ...postTypes
                        ]}
                        onChange={(value) => setAttributes({ postType: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <TextControl
                        label={__('Comments Per Page', 'wpuf-pro')}
                        value={commentsPerPage}
                        onChange={(value) => setAttributes({ commentsPerPage: parseInt(value) || 10 })}
                        type="number"
                        min={1}
                        max={50}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Show Pagination', 'wpuf-pro')}
                        checked={showPagination}
                        onChange={(value) => setAttributes({ showPagination: value })}
                        help={__('Display pagination controls when there are multiple pages of comments.', 'wpuf-pro')}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />
                </PanelBody>
                <PanelBody title={__('Visibility', 'wpuf-pro')} initialOpen={false}>
                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Profile User Role', 'wpuf-pro')}</label>
                        <MultiSelect
                            options={roleOptions}
                            value={selectedRoles}
                            onChange={(value) => setAttributes({ profileUserRoles: value })}
                            placeholder={__('All Roles', 'wpuf-pro')}
                            sortable={false}
                            searchable={true}
                        />
                        <p className="components-base-control__help">{__('Show this block only for users with these roles.', 'wpuf-pro')}</p>
                    </div>

                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Viewer Role', 'wpuf-pro')}</label>
                        <MultiSelect
                            options={roleOptions}
                            value={selectedViewerRoles}
                            onChange={(value) => setAttributes({ viewerRoles: value })}
                            placeholder={__('All Roles', 'wpuf-pro')}
                            sortable={false}
                            searchable={true}
                        />
                        <p className="components-base-control__help">{__('Show this block only to viewers with these roles. Include "Guest" for non-logged-in users.', 'wpuf-pro')}</p>
                    </div>
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                {isLoading && (
                    <div className="wpuf-px-4 wpuf-py-8 wpuf-text-center">
                        <p className="wpuf-text-gray-500">
                            {__('Loading comments...', 'wpuf-pro')}
                        </p>
                    </div>
                )}

                {error && (
                    <div className="wpuf-px-4 wpuf-py-8 wpuf-text-center">
                        <p className="wpuf-text-red-500">
                            {error}
                        </p>
                    </div>
                )}

                {!isLoading && !error && comments.length > 0 && roleAllowed && viewerAllowed && (
                    <div className="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg">
                        <div className="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white">
                            {comments.map((comment) => (
                                <div key={comment.id} className="wpuf-px-4 wpuf-py-4">
                                    <div className="wpuf-flex wpuf-items-start wpuf-gap-3">
                                        <div className="wpuf-flex-shrink-0">
                                            <div className="wpuf-w-8 wpuf-h-8 wpuf-rounded-full wpuf-flex wpuf-items-center wpuf-justify-center">
                                                <span className="wpuf-text-xs wpuf-font-medium wpuf-text-gray-600">
                                                    {user.display_name.charAt(0).toUpperCase()}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="wpuf-flex-1 wpuf-min-w-0">
                                            <div className="wpuf-flex wpuf-items-center wpuf-gap-2 wpuf-mb-1">
                                                <span className="wpuf-text-sm wpuf-font-medium wpuf-text-gray-900">
                                                    {user.display_name}
                                                </span>
                                                <span className="wpuf-text-xs wpuf-text-gray-500">
                                                    {new Date(comment.date).toLocaleDateString('en-US', {
                                                        year: 'numeric',
                                                        month: 'short',
                                                        day: 'numeric'
                                                    })}
                                                </span>
                                            </div>
                                            <p className="wpuf-text-sm wpuf-text-gray-700 wpuf-mb-2">
                                                {comment.content.rendered ?
                                                    comment.content.rendered.replace(/<[^>]*>/g, '').substring(0, 150) + '...' :
                                                    comment.content.substring(0, 150) + '...'
                                                }
                                            </p>
                                            <div className="wpuf-flex wpuf-items-center wpuf-gap-4 wpuf-text-xs wpuf-text-gray-500">
                                                <span>
                                                    {__('On', 'wpuf-pro')}: <a href="#" className="wpuf-text-indigo-600 wpuf-hover:text-indigo-900">
                                                        {comment.post_title || __('Unknown Post', 'wpuf-pro')}
                                                    </a>
                                                </span>
                                                {comment.reply_count > 0 && (
                                                    <span>
                                                        {comment.reply_count} {__('replies', 'wpuf-pro')}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {!isLoading && !error && comments.length === 0 && roleAllowed && viewerAllowed && (
                    <div className="wpuf-px-4 wpuf-py-8 wpuf-text-center">
                        <p className="wpuf-text-gray-500">
                            {__('No comments found for this user.', 'wpuf-pro')}
                        </p>
                    </div>
                )}

                {!isLoading && !error && !roleAllowed && (
                    <div className="wpuf-px-4 wpuf-py-8 wpuf-text-center">
                        <p className="wpuf-text-gray-500">
                            {__('Hidden for this user role.', 'wpuf-pro')}
                        </p>
                    </div>
                )}
            </div>
        </Fragment>
    );
};

export default Edit;
