// User Tabs Edit Component
// Displays and configures user tabs with simplified management

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps,
    InnerBlocks
} from '@wordpress/block-editor';
import { select } from '@wordpress/data';
import {
    PanelBody,
    Notice,
    TextControl,
    ToggleControl
} from '@wordpress/components';
import { Fragment, useEffect, useState } from '@wordpress/element';
import TabManager from '../../components/TabManager';



// Import tab utilities
import { getAvailableTabs, getVisibleTabs, getTabLabel } from '../../utils/tab-utils';

// Get allowed blocks by filtering out disallowed blocks
const getAllowedBlocks = (disallowedBlocks = []) => {
    // Get all registered blocks
    const allBlockTypes = select('core/blocks')?.getBlockTypes() || [];

    // Filter out disallowed blocks, but always allow WPUF blocks except the explicitly disallowed ones
    const allowedBlockNames = allBlockTypes
        .map(blockType => blockType.name)
        .filter(blockName => {
            // Always allow WPUF blocks unless explicitly disallowed
            if (blockName.startsWith('wpuf-ud/')) {
                return !disallowedBlocks.includes(blockName);
            }
            // Allow all other blocks
            return true;
        });

    return allowedBlockNames;
};

const TabManagementPanel = ({ enabledTabs, tabOrder, customLabels, setAttributes }) => {
    const handleTabUpdate = (updates) => {
        setAttributes(updates);
    };

    return (
        <PanelBody title={__('Tab Management', 'wpuf-pro')} initialOpen={true}>
            <Notice status="info" isDismissible={false}>
                {__('Drag tabs to reorder, click the pencil to rename, and use toggles to enable/disable tabs.', 'wpuf-pro')}
            </Notice>

            <TabManager
                enabledTabs={enabledTabs || []}
                tabOrder={tabOrder || []}
                customLabels={customLabels || {}}
                onChange={handleTabUpdate}
                sortable={true}
                editable={true}
            />
        </PanelBody>
    );
};

const PostsPaginationPanel = ({ postsPerPage, showPostsPagination, setAttributes }) => {
    return (
        <PanelBody title={__('Posts Pagination', 'wpuf-pro')} initialOpen={false}>
            <TextControl
                label={__('Posts Per Page', 'wpuf-pro')}
                value={postsPerPage || 10}
                onChange={(value) => setAttributes({ postsPerPage: parseInt(value) || 10 })}
                type="number"
                min="1"
                max="100"
                help={__('Number of posts to display per page', 'wpuf-pro')}
            />
            <ToggleControl
                label={__('Show Post Pagination', 'wpuf-pro')}
                checked={showPostsPagination !== false}
                onChange={(value) => setAttributes({ showPostsPagination: value })}
                help={__('Display pagination controls for posts', 'wpuf-pro')}
            />
        </PanelBody>
    );
};

const CommentsPaginationPanel = ({ commentsPerPage, showCommentsPagination, setAttributes }) => {
    return (
        <PanelBody title={__('Comments Pagination', 'wpuf-pro')} initialOpen={false}>
            <TextControl
                label={__('Comments Per Page', 'wpuf-pro')}
                value={commentsPerPage || 10}
                onChange={(value) => setAttributes({ commentsPerPage: parseInt(value) || 10 })}
                type="number"
                min="1"
                max="100"
                help={__('Number of comments to display per page', 'wpuf-pro')}
            />
            <ToggleControl
                label={__('Show Comment Pagination', 'wpuf-pro')}
                checked={showCommentsPagination !== false}
                onChange={(value) => setAttributes({ showCommentsPagination: value })}
                help={__('Display pagination controls for comments', 'wpuf-pro')}
            />
        </PanelBody>
    );
};

const Edit = ({ attributes, setAttributes, context, clientId }) => {
    const { 
        enabledTabs, 
        tabOrder, 
        customLabels, 
        disallowedBlocks, 
        aboutTabContent,
        postsPerPage,
        showPostsPagination,
        commentsPerPage,
        showCommentsPagination
    } = attributes;

    // Normalize attributes on first render without mutating saved intent
    useEffect(() => {
        const available = getAvailableTabs();
        const updates = {};
        let needUpdate = false;

        if (!Array.isArray(tabOrder) || tabOrder.length === 0) {
            updates.tabOrder = Object.keys(available);
            needUpdate = true;
        }

        if (!Array.isArray(enabledTabs)) {
            updates.enabledTabs = Object.keys(available);
            needUpdate = true;
        }

        if (!customLabels || typeof customLabels !== 'object') {
            updates.customLabels = {};
            needUpdate = true;
        }

        if (!Array.isArray(disallowedBlocks)) {
            updates.disallowedBlocks = ['wpuf-ud/directory', 'wpuf-ud/profile', 'wpuf-ud/tabs'];
            needUpdate = true;
        }

        if (!Array.isArray(aboutTabContent)) {
            updates.aboutTabContent = [];
            needUpdate = true;
        }

        if (typeof postsPerPage !== 'number' || postsPerPage < 1) {
            updates.postsPerPage = 10;
            needUpdate = true;
        }

        if (typeof showPostsPagination !== 'boolean') {
            updates.showPostsPagination = true;
            needUpdate = true;
        }

        if (typeof commentsPerPage !== 'number' || commentsPerPage < 1) {
            updates.commentsPerPage = 10;
            needUpdate = true;
        }

        if (typeof showCommentsPagination !== 'boolean') {
            updates.showCommentsPagination = true;
            needUpdate = true;
        }

        if (needUpdate) {
            setAttributes(updates);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const blockProps = useBlockProps();

    // Get visible tabs (enabled tabs that are available) in correct order
    const availableTabs = getAvailableTabs();
    const visibleTabs = getVisibleTabs(enabledTabs || [], tabOrder || [], availableTabs);

    // Use the first visible tab as the default active tab
    const activeTab = visibleTabs.length > 0 ? visibleTabs[0] : 'about';

    // Editor-only state: which tab is previewed as active
    const [previewActiveTab, setPreviewActiveTab] = useState(activeTab);

    // Keep previewActiveTab in sync if tabs change or current becomes unavailable
    useEffect(() => {
        if (!visibleTabs.includes(previewActiveTab)) {
            setPreviewActiveTab(activeTab);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [enabledTabs, tabOrder]);

    // Sample content for preview of fixed tabs
    const getTabContent = (tabId) => {
        switch (tabId) {
            case 'posts':
                return __('This tab will display the user\'s posts. Content is automatically generated on the frontend.', 'wpuf-pro');
            case 'comments':
                return __('This tab will display the user\'s comments. Content is automatically generated on the frontend.', 'wpuf-pro');
            case 'files':
                return __('This tab will display the user\'s uploaded files. Content is automatically generated on the frontend.', 'wpuf-pro');
            case 'activity':
                return __('This tab will display the user\'s activity. Content is automatically generated on the frontend.', 'wpuf-pro');
            default:
                return __('Tab content will be loaded dynamically on the frontend.', 'wpuf-pro');
        }
    };

    // Handle About tab content changes
    const handleAboutTabContentChange = (newBlocks) => {
        setAttributes({ aboutTabContent: newBlocks });
    };

    return (
        <Fragment>
            <InspectorControls>
                <TabManagementPanel
                    enabledTabs={enabledTabs || []}
                    tabOrder={tabOrder || []}
                    customLabels={customLabels || {}}
                    setAttributes={setAttributes}
                />
                
                {/* Posts Pagination Settings - Only show when posts tab is enabled */}
                {enabledTabs && enabledTabs.includes('posts') && (
                    <PostsPaginationPanel
                        postsPerPage={postsPerPage}
                        showPostsPagination={showPostsPagination}
                        setAttributes={setAttributes}
                    />
                )}
                
                {/* Comments Pagination Settings - Only show when comments tab is enabled */}
                {enabledTabs && enabledTabs.includes('comments') && (
                    <CommentsPaginationPanel
                        commentsPerPage={commentsPerPage}
                        showCommentsPagination={showCommentsPagination}
                        setAttributes={setAttributes}
                    />
                )}
            </InspectorControls>

            <div {...blockProps}>
                <div className="wpuf-user-tabs">
                    {/* Tab Navigation - Always visible in editor */}
                    <div className="wpuf-block">
                        <div className="wpuf-border-b wpuf-border-gray-200">
                            <nav aria-label={__('Tabs', 'wpuf-pro')} className="wpuf--mb-px wpuf-flex">
                                {visibleTabs.map((tabId) => (
                                    <button
                                        key={tabId}
                                        className={`wpuf-w-1/${visibleTabs.length} wpuf-border-b-2 wpuf-px-1 wpuf-py-4 wpuf-text-center wpuf-text-sm wpuf-font-medium ${
                                            previewActiveTab === tabId
                                                ? 'wpuf-border-current wpuf-text-current'
                                                : 'wpuf-border-transparent wpuf-text-gray-500 hover:wpuf-border-gray-300 hover:wpuf-text-gray-700'
                                        }`}
                                        onClick={() => {
                                            setPreviewActiveTab(tabId);
                                        }}
                                        aria-current={previewActiveTab === tabId ? 'page' : undefined}
                                    >
                                        {getTabLabel(tabId, customLabels || {}, availableTabs)}
                                    </button>
                                ))}
                            </nav>
                        </div>
                    </div>

                    {/* Tab Content */}
                    <div className="wpuf-tab-content-area wpuf-mt-6">
                        {(() => {
                            const activeTabId = previewActiveTab;
                            return (
                                <div className="wpuf-tab-content wpuf-tab-active">
                                    {activeTabId === 'about' ? (
                                        <div className="wpuf-about-tab-content">
                                            <InnerBlocks
                                                allowedBlocks={getAllowedBlocks(disallowedBlocks || [])}
                                                template={[]}
                                                templateLock={false}
                                                onInput={handleAboutTabContentChange}
                                                value={aboutTabContent || []}
                                            />
                                        </div>
                                    ) : (
                                        <div className="wpuf-tab-preview">
                                            <h4 className="wpuf-tab-title">
                                                {getTabLabel(activeTabId, customLabels || {}, availableTabs)}
                                            </h4>
                                            <div className="wpuf-tab-text">
                                                {getTabContent(activeTabId)}
                                            </div>
                                            <div className="wpuf-tab-note">
                                                <em>{__('Content will be loaded dynamically on the frontend', 'wpuf-pro')}</em>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            );
                        })()}
                    </div>
                </div>
            </div>
        </Fragment>
    );
};

export default Edit;
