import { Modal, Button, TextControl, ButtonGroup } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { parse } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useState, useMemo } from '@wordpress/element';
import { Icon, search } from '@wordpress/icons';

const LibraryModal = ({ isOpen, onClose }) => {
    const [activeTab, setActiveTab] = useState('sections'); // 'sections' or 'pages'
    const [activeCategory, setActiveCategory] = useState('all');
    const [searchQuery, setSearchQuery] = useState('');

    const { patterns } = useSelect((select) => {
        const allPatterns = select('core').getBlockPatterns() || [];

        const pluginPatterns = allPatterns.filter(p =>
            p.categories && p.categories.includes('author-website-templates')
        );

        return { patterns: pluginPatterns };
    }, []);

    const getPatternImage = (patternName) => {
        const cleanSlug = patternName.replace('author-website-templates/', '').replace('awt/', '');
        const baseUrl = window.awtVars?.patternImagesUrl || '';

        return `${baseUrl}${cleanSlug}.jpg`;
    };

    const handleImageError = (e) => {
        e.target.style.display = 'none';
        e.target.nextSibling.style.display = 'flex';
    };
    const filteredPatterns = useMemo(() => {
        return patterns.filter(pattern => {
            const isFullPage = pattern.keywords?.includes('full-page');
            const matchesTab = activeTab === 'pages' ? isFullPage : !isFullPage;

            const matchesSearch = pattern.title.toLowerCase().includes(searchQuery.toLowerCase());
            const matchesCategory = activeCategory === 'all' || pattern.keywords?.includes(activeCategory);

            return matchesTab && matchesSearch && matchesCategory;
        });
    }, [patterns, activeTab, searchQuery, activeCategory]);

    const categories = useMemo(() => {
        const cats = new Set(['all']);
        patterns.forEach(p => {
            const isPage = p.keywords?.includes('full-page');
            if ((activeTab === 'pages' && isPage) || (activeTab === 'sections' && !isPage)) {
                p.keywords?.forEach(k => k !== 'full-page' && cats.add(k));
                p.keywords?.forEach(k => k !== 'full-page' && cats.add(k));
            }
        });
        return Array.from(cats);
    }, [patterns, activeTab]);

    const { insertBlocks } = useDispatch('core/block-editor');

    const importPattern = (pattern) => {
        const blocks = parse(pattern.content);
        insertBlocks(blocks);
        onClose();
    };

    if (!isOpen) return null;

    return (
        <Modal
            title={null}
            onRequestClose={onClose}
            className="awt-library-modal"
            overlayClassName="awt-library-overlay"
        >
            <div className="awt-library-header">
                <div className="awt-header-left">
                    <h2 className="awt-brand">Author Website Templates Library</h2>
                    <div className="awt-tabs">
                        <button
                            className={`awt-tab ${activeTab === 'sections' ? 'active' : ''}`}
                            onClick={() => { setActiveTab('sections'); setActiveCategory('all'); }}
                        >
                            Sections
                        </button>
                        <button
                            className={`awt-tab ${activeTab === 'pages' ? 'active' : ''}`}
                            onClick={() => { setActiveTab('pages'); setActiveCategory('all'); }}
                        >
                            Pages
                        </button>
                    </div>
                </div>
                <div className="awt-header-right">
                    <div className="awt-search-wrapper">
                        <Icon icon={search} />
                        <input
                            type="text"
                            placeholder="Search templates..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                    </div>
                    <Button icon="no-alt" onClick={onClose} label="Close" />
                </div>
            </div>

            {/* --- Body Area --- */}
            <div className="awt-library-body">

                {/* Sidebar Filters */}
                <div className="awt-library-sidebar">
                    <h3>Categories</h3>
                    <ul>
                        {categories.map(cat => (
                            <li key={cat}>
                                <button
                                    className={activeCategory === cat ? 'active' : ''}
                                    onClick={() => setActiveCategory(cat)}
                                >
                                    {cat.charAt(0).toUpperCase() + cat.slice(1)}
                                </button>
                            </li>
                        ))}
                    </ul>
                </div>

                {/* Main Grid */}
                <div className="awt-library-content">
                    {filteredPatterns.length > 0 ? (
                        <div className="awt-template-grid">
                            {filteredPatterns.map((pattern) => {
                                const isFullPage = pattern.keywords?.includes('full-page');
                                return (
                                    <div key={pattern.name} className="awt-template-card">
                                        <div className={`awt-card-preview ${isFullPage ? 'is-full-page' : ''}`}>
                                            <img
                                                src={getPatternImage(pattern.name)}
                                                alt={pattern.title}
                                                onError={handleImageError}
                                                className="awt-pattern-img"
                                            />
                                            <div className="placeholder-preview" style={{ display: 'none' }}>
                                                {pattern.title.charAt(0)}
                                            </div>
                                            <div className="awt-card-overlay">
                                                <Button variant="primary" onClick={() => importPattern(pattern)}>
                                                    Insert
                                                </Button>
                                            </div>
                                        </div>
                                        <div className="awt-card-footer">
                                            <h4>{pattern.title}</h4>
                                            {isFullPage && <span className="awt-badge">Page</span>}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ) : (
                        <div className="awt-empty-state">
                            <p>No templates found matching your criteria.</p>
                        </div>
                    )}
                </div>
            </div>
        </Modal>
    );
};

export default LibraryModal;