// User Posts Edit Component
// Displays and configures user posts with various display options

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

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

    const [posts, setPosts] = 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, excluding unwanted types
    const excludedPostTypes = ['page', 'attachment', 'wpuf_subscription'];
    const allPostTypes = window.wpufUserDirectory?.postTypes || [
        { label: __('Posts', 'wpuf-pro'), value: 'post' },
        { label: __('Pages', 'wpuf-pro'), value: 'page' }
    ];
    
    const postTypes = allPostTypes.filter(postType => 
        !excludedPostTypes.includes(postType.value)
    );

    // Function to get dynamic post type label
    const getPostTypeLabel = (postTypeValue) => {
        const postTypeObj = allPostTypes.find(pt => pt.value === postTypeValue);
        if (postTypeObj) {
            // For singular form, we'll use the label and add "Title" suffix
            // This handles cases like "Post" -> "Post Title", "Product" -> "Product Title", "Book" -> "Book Title"
            return `${postTypeObj.label} ${__('Title', 'wpuf-pro')}`;
        }
        // Fallback to generic "Post Title" if post type not found
        return __('Post Title', 'wpuf-pro');
    };

    // 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 posts for the user
    useEffect(() => {
        const fetchPosts = async () => {
            if (!user.id || user.id === 0) {
                // Show sample data for preview when no real user
                setPosts([
                    {
                        id: 1,
                        title: { rendered: __('Sample Post Title 1', 'wpuf-pro') },
                        date: '2026-01-15T10:00:00',
                        link: '#',
                        excerpt: { rendered: __('This is a sample post excerpt that demonstrates how the user posts block will display content.', 'wpuf-pro') }
                    },
                    {
                        id: 2,
                        title: { rendered: __('Sample Post Title 2', 'wpuf-pro') },
                        date: '2026-01-10T14:30:00',
                        link: '#',
                        excerpt: { rendered: __('Another sample post excerpt to show how multiple posts would appear in the user posts block.', 'wpuf-pro') }
                    }
                ]);
                setIsLoading(false);
                return;
            }

            setIsLoading(true);
            setError('');

            try {
                // Use the correct REST API endpoint based on post type
                // For 'post' type, use /wp/v2/posts, for other types use /wp/v2/{post_type}
                const endpoint = postType === 'post' ? 'posts' : postType;
                const response = await fetch(`/wp-json/wp/v2/${endpoint}?author=${user.id}&per_page=${postsPerPage}&orderby=date&order=desc&_embed`);

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                if (Array.isArray(data)) {
                    setPosts(data);
                } else {
                    setPosts([]);
                }
            } catch (err) {
                setError(__('Failed to load posts', 'wpuf-pro'));
                // Fallback to sample data on error
                setPosts([
                    {
                        id: 1,
                        title: { rendered: __('Sample Post Title 1', 'wpuf-pro') },
                        date: '2024-01-15T10:00:00',
                        link: '#',
                        excerpt: { rendered: __('This is a sample post excerpt that demonstrates how the user posts block will display content.', 'wpuf-pro') }
                    },
                    {
                        id: 2,
                        title: { rendered: __('Sample Post Title 2', 'wpuf-pro') },
                        date: '2024-01-10T14:30:00',
                        link: '#',
                        excerpt: { rendered: __('Another sample post excerpt to show how multiple posts would appear in the user posts block.', 'wpuf-pro') }
                    }
                ]);
            } finally {
                setIsLoading(false);
            }
        };

        fetchPosts();
    }, [user.id, postType, postsPerPage]);

    // 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={__('Posts Settings', 'wpuf-pro')} initialOpen={true}>
                    <SelectControl
                        label={__('Post Type', 'wpuf-pro')}
                        value={postType}
                        options={postTypes}
                        onChange={(value) => setAttributes({ postType: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <TextControl
                        label={__('Posts Per Page', 'wpuf-pro')}
                        value={postsPerPage}
                        onChange={(value) => setAttributes({ postsPerPage: 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 posts.', '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 posts...', '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 && posts.length > 0 && roleAllowed && viewerAllowed && (
                    <div className="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg">
                        <table className="wpuf-relative wpuf-min-w-full wpuf-divide-y wpuf-divide-gray-300">
                            <thead className="wpuf-bg-gray-50">
                                <tr>
                                    <th scope="col" className="wpuf-py-3.5 wpuf-pr-3 wpuf-pl-4 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900 wpuf-sm:pl-6">
                                        {wp.hooks.applyFilters('wpuf.userPosts.titleLabel', getPostTypeLabel(postType), postType)}
                                    </th>
                                    <th scope="col" className="wpuf-px-3 wpuf-py-3.5 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900">
                                        {wp.hooks.applyFilters('wpuf.userPosts.publishDateLabel', __('Publish Date', 'wpuf-pro'), postType)}
                                    </th>
                                    <th scope="col" className="wpuf-py-3.5 wpuf-pr-4 wpuf-pl-3 wpuf-sm:pr-6">
                                        <span className="wpuf-sr-only">{__('View', 'wpuf-pro')}</span>
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white">
                                {posts.map((post) => (
                                    <tr key={post.id}>
                                        <td className="wpuf-py-4 wpuf-pr-3 wpuf-pl-4 wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-text-gray-900 wpuf-sm:pl-6">
                                            {post.title.rendered}
                                        </td>
                                        <td className="wpuf-px-3 wpuf-py-4 wpuf-text-sm wpuf-whitespace-nowrap wpuf-text-gray-500">
                                            {new Date(post.date).toLocaleDateString('en-US', {
                                                year: 'numeric',
                                                month: 'long',
                                                day: 'numeric'
                                            })}
                                        </td>
                                        <td className="wpuf-py-4 wpuf-pr-4 wpuf-pl-3 wpuf-text-right wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-sm:pr-6">
                                            <a
                                                href={post.link}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="wpuf-text-indigo-600 wpuf-hover:text-indigo-900"
                                            >
                                                { __('Link ->', 'wpuf-pro') }
                                                <span className="wpuf-sr-only">, {post.title.rendered}</span>
                                            </a>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {!isLoading && !error && posts.length === 0 && roleAllowed && viewerAllowed && (
                    <div className="wpuf-px-4 wpuf-py-8 wpuf-text-center">
                        <p className="wpuf-text-gray-500">
                            {__('No posts 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;
