const { registerBlockType } = wp.blocks;
const { InspectorControls } = wp.blockEditor;
const { PanelBody, RangeControl, ToggleControl, SelectControl, TextControl } = wp.components;
const { __ } = wp.i18n;
const { useState, useEffect } = wp.element;

registerBlockType('launchmind/blog-list', {
    title: __('Launchmind Blog', 'launchmind-blog'),
    icon: 'rss',
    category: 'launchmind',
    keywords: [__('blog', 'launchmind-blog'), __('posts', 'launchmind-blog'), __('launchmind', 'launchmind-blog'), __('articles', 'launchmind-blog')],
    description: __('Display Launchmind blog posts in a grid or list.', 'launchmind-blog'),
    supports: { align: ['wide', 'full'], html: false },
    attributes: {
        postsLimit: { type: 'number', default: 6 },
        columns: { type: 'number', default: 3 },
        layout: { type: 'string', default: 'grid' },
        showExcerpt: { type: 'boolean', default: true },
        showDate: { type: 'boolean', default: true },
        showImage: { type: 'boolean', default: true },
        showReadMore: { type: 'boolean', default: true },
        cardStyle: { type: 'string', default: 'elevated' },
        heading: { type: 'string', default: 'Latest from our Blog' },
        subtitle: { type: 'string', default: '' },
        showBranding: { type: 'boolean', default: false },
    },
    edit: (props) => {
        const { attributes, setAttributes } = props;
        const [posts, setPosts] = useState([]);
        const [loading, setLoading] = useState(true);

        useEffect(() => {
            setLoading(true);
            fetch(launchmindBlock.ajaxUrl + '?action=launchmind_get_posts_preview&nonce=' + launchmindBlock.nonce + '&limit=' + attributes.postsLimit)
                .then((r) => r.json())
                .then((data) => {
                    setPosts(data && data.data && data.data.posts ? data.data.posts : []);
                    setLoading(false);
                })
                .catch(() => setLoading(false));
        }, [attributes.postsLimit]);

        return (
            <>
                <InspectorControls>
                    <PanelBody title={__('Header', 'launchmind-blog')}>
                        <TextControl
                            label={__('Heading', 'launchmind-blog')}
                            value={attributes.heading}
                            onChange={(val) => setAttributes({ heading: val })}
                        />
                        <TextControl
                            label={__('Subtitle', 'launchmind-blog')}
                            value={attributes.subtitle}
                            onChange={(val) => setAttributes({ subtitle: val })}
                        />
                    </PanelBody>
                    <PanelBody title={__('Layout', 'launchmind-blog')}>
                        <SelectControl
                            label={__('Layout', 'launchmind-blog')}
                            value={attributes.layout}
                            options={[
                                { label: __('Grid', 'launchmind-blog'), value: 'grid' },
                                { label: __('List', 'launchmind-blog'), value: 'list' },
                            ]}
                            onChange={(val) => setAttributes({ layout: val })}
                        />
                        <RangeControl
                            label={__('Number of posts', 'launchmind-blog')}
                            value={attributes.postsLimit}
                            onChange={(val) => setAttributes({ postsLimit: val })}
                            min={1}
                            max={12}
                        />
                        <RangeControl
                            label={__('Columns (desktop)', 'launchmind-blog')}
                            value={attributes.columns}
                            onChange={(val) => setAttributes({ columns: val })}
                            min={1}
                            max={4}
                        />
                    </PanelBody>
                    <PanelBody title={__('Card', 'launchmind-blog')}>
                        <SelectControl
                            label={__('Card style', 'launchmind-blog')}
                            value={attributes.cardStyle}
                            options={[
                                { label: __('Elevated', 'launchmind-blog'), value: 'elevated' },
                                { label: __('Bordered', 'launchmind-blog'), value: 'bordered' },
                                { label: __('Minimal', 'launchmind-blog'), value: 'minimal' },
                            ]}
                            onChange={(val) => setAttributes({ cardStyle: val })}
                        />
                        <ToggleControl
                            label={__('Show image', 'launchmind-blog')}
                            checked={attributes.showImage}
                            onChange={(val) => setAttributes({ showImage: val })}
                        />
                        <ToggleControl
                            label={__('Show date', 'launchmind-blog')}
                            checked={attributes.showDate}
                            onChange={(val) => setAttributes({ showDate: val })}
                        />
                        <ToggleControl
                            label={__('Show excerpt', 'launchmind-blog')}
                            checked={attributes.showExcerpt}
                            onChange={(val) => setAttributes({ showExcerpt: val })}
                        />
                        <ToggleControl
                            label={__('Show read more', 'launchmind-blog')}
                            checked={attributes.showReadMore}
                            onChange={(val) => setAttributes({ showReadMore: val })}
                        />
                        <ToggleControl
                            label={__('Show branding', 'launchmind-blog')}
                            checked={attributes.showBranding}
                            onChange={(val) => setAttributes({ showBranding: val })}
                        />
                    </PanelBody>
                </InspectorControls>

                <div className={`lm-block-preview lm-columns-${attributes.columns} lm-layout-${attributes.layout}`}>
                    {attributes.heading && <h3>{attributes.heading}</h3>}
                    {attributes.subtitle && <p className="description">{attributes.subtitle}</p>}
                    {loading ? (
                        <p>{__('Loading posts...', 'launchmind-blog')}</p>
                    ) : posts.length === 0 ? (
                        <p>{__('No posts found. Configure your API key in settings.', 'launchmind-blog')}</p>
                    ) : (
                        <div className={`lm-block-grid lm-block-grid--${attributes.layout}`}>
                            {posts.slice(0, attributes.postsLimit).map((post) => (
                                <div key={post.slug} className={`lm-block-card lm-block-card--${attributes.cardStyle}`}>
                                    {attributes.showImage && post.coverImage && <img src={post.coverImage} alt={post.title} />}
                                    <div className="lm-block-card__content">
                                        {attributes.showDate && post.publishedAt && (
                                            <span className="lm-block-card__date">{new Date(post.publishedAt).toLocaleDateString()}</span>
                                        )}
                                        <h4>{post.title}</h4>
                                        {attributes.showExcerpt && post.excerpt && <p>{post.excerpt.substring(0, 80)}...</p>}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                    {attributes.showBranding && <div className="lm-block-branding">{__('Blog powered by Launchmind.io', 'launchmind-blog')}</div>}
                </div>
            </>
        );
    },
    save: () => null,
});
