import Flickity from 'flickity';
import 'flickity/dist/flickity.min.css';
import { useEffect, useState, useRef } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { PanelBody, ToggleControl, TextControl, SelectControl  } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import metadata from './block.json';

const { registerBlockType } = wp.blocks;

registerBlockType(metadata.name, {
    title: __('FlexiFlick Slider', 'flexiflick'),
    icon: 'slides',
    category: 'widgets',
    attributes: {
        sliderGroup: {
            type: 'string',
            default: '',
        },
        showArrows: {
            type: 'boolean',
            default: true,
        },
        showPager: {
            type: 'boolean',
            default: true,
        },
        draggable: {
            type: 'boolean',
            default: false,
        },
        wrapAround: {
            type: 'boolean',
            default: false,
        },
        freeScroll: {
            type: 'boolean',
            default: true,
        },
        pauseAutoPlayOnHover: {
            type: 'boolean',
            default: false,
        },
        autoPlay: {
            type: 'number',   // Number input for autoPlay
            default: 0,
        },
        minHeight: {
            type: 'number',   // Number input for autoPlay
            default: 450,
        },
    },
edit({ attributes, setAttributes }) {
    const blockProps = useBlockProps();
    const sliderRef = useRef();

    // Fetch the custom post type content
    const posts = useSelect((select) => {
        const fetchedPosts = select('core').getEntityRecords('postType', 'flexiflick_slide_cpt', {
            per_page: 3, // Limit the number of posts for the preview
            _embed: true, // Embed related resources, such as the featured media
        });

        if (fetchedPosts) {
            return fetchedPosts.map((post) => ({
                id: post.id,
                title: post.title.rendered,
                content: post.content.rendered, // Use the body content instead of the excerpt
                featured_media_url: post._embedded?.['wp:featuredmedia']?.[0]?.source_url || '',
            }));
        }

        return [];
    }, []);

    const [sliderGroups, setSliderGroups] = useState([]);

    // Fetch available slider groups
    useEffect(() => {
            wp.apiFetch({ path: '/wp/v2/flexiflick_slider_group' }).then((groups) => {
                setSliderGroups(groups.map((group) => ({
                    label: group.name,
                    value: group.id,
                })));
            });
        }, []);

    useEffect(() => {
            // Initialize Flickity only if posts are loaded
            if (posts.length > 0 && sliderRef.current) {
                const flickityInstance = new Flickity(sliderRef.current, {
                    prevNextButtons: attributes.showArrows,
                    pageDots: attributes.showPager,
                });

                return () => {
                    flickityInstance.destroy();
                };
            }
        }, [attributes.showArrows, attributes.showPager, posts]);


    return (
        <div {...blockProps}>
                <InspectorControls>
                    <PanelBody title={__('Slider Settings', 'flexiflick')}>
                        <ToggleControl
                            label={__('Show Arrows', 'flexiflick')}
                            help={__('Enter the autoPlay speed in milliseconds. For example 1500 will advance cells every 1.5 seconds. Set to 0 for no autoPlay.', 'flexiflick')}
                            checked={attributes.showArrows}
                            onChange={(value) => setAttributes({ showArrows: value })}
                        />
                        <SelectControl
                            label="Select Slider Group"
                            value={attributes.sliderGroup}
                            options={[
                                { label: 'Select a group', value: '' },
                                ...sliderGroups,
                            ]}
                            onChange={(value) =>
                                setAttributes({ sliderGroup: value })
                            }
                        />
                        <ToggleControl
                            label={__('Show Pager', 'flexiflick')}
                            help={__('Enter the autoPlay speed in milliseconds. Set to 0 for no autoPlay.', 'flexiflick')}
                            checked={attributes.showPager}
                            onChange={(value) => setAttributes({ showPager: value })}
                        />
                        <ToggleControl
                            label={__('Wrap Around', 'flexiflick')}
                            help={__('At the end of cells, wrap-around to the other end for infinite scrolling.', 'flexiflick')}
                            checked={attributes.wrapAround}
                            onChange={(value) => setAttributes({ wrapAround: value })}
                        />
                        <ToggleControl
                            label={__('Draggable', 'flexiflick')}
                            help={__('Enables dragging and flicking. Enabled by default when carousel has 2 or more slides. more detail can be found here https://flickity.metafizzy.co/options', 'flexiflick')}
                            checked={attributes.draggable}
                            onChange={(value) => setAttributes({ draggable: value })}
                        />
                        <ToggleControl
                            label={__('Free Scroll', 'flexiflick')}
                            help={__('Enables content to be freely scrolled and flicked without aligning cells to an end position.', 'flexiflick')}

                            checked={attributes.freeScroll}
                            onChange={(value) => setAttributes({ freeScroll: value })}
                        />
                        <ToggleControl
                            label={__('Pause Auto Play On Hover', 'flexiflick')}
                            help={__('Auto-playing will pause when the user hovers over the carousel.', 'flexiflick')}
                            checked={attributes.pauseAutoPlayOnHover}
                            onChange={(value) => setAttributes({ pauseAutoPlayOnHover: value })}
                        />
                        <TextControl
                            label={__('AutoPlay Speed (ms)', 'flexiflick')}
                            help={__('Enter the autoPlay speed in milliseconds. Set to 0 for no autoPlay.', 'flexiflick')}
                            value={attributes.autoPlay}
                            onChange={(autoPlay) => setAttributes({ autoPlay: parseInt(autoPlay) || 0 })}
                            type="number"
                        />
                        <TextControl
                            label={__('Min Height (px)', 'flexiflick')}
                            help={__('Enter the minimum height in pixels for slider', 'flexiflick')}
                            value={attributes.minHeight}
                            onChange={(minHeight) => setAttributes({ minHeight: parseInt(minHeight) || 450 })}
                            type="number"
                        />
                    </PanelBody>
                </InspectorControls>
                <div className="flickity-placeholder">
                    <div  ref={sliderRef}>
                            <div className="flickity-placeholder-content">
                                <h3>Flickity Responsive Slider/Carousel</h3>
                                {attributes.sliderGroup && (
                                    <p>Selected Group ID: {attributes.sliderGroup}</p>
                                )}
                                <p>....................................</p>
                                <p>{`{ showArrows: ${attributes.showArrows ? 'True' : 'False'} }`}</p>
                                <p>{`{ showPager: ${attributes.showPager ? 'True' : 'False'} }`}</p>
                            </div>
                    </div>
                </div>
            </div>
    );
    },
    save() {
        return null; // Rendered on the server.
    },
});
