const { __ } = wp.i18n;
const { useState, useEffect, useContext, useRef, memo } = wp.element;

// import { AppContext } from "../../AppContext";
import Icon from "../Icon";
import Panel from "../panels/Panel";
import SimpleColorPicker from "./SimpleColorPicker";
import SegmentedButtons from "./SegmentedButtons";
import MandatoryCheckboxGroup from "./MandatoryCheckboxGroup";
import SafiInput from "../ui/SafiInput";
import TextRadioGroup from "./TextRadioGroup";
import SafiSwitch from "./SafiSwitch";
import DynamicText from "./DynamicText";
import SafiTooltip from "../ui/SafiTooltip";

const sources = [
    {
        value: 'unsplash',
        label: 'Unsplash',
        url: 'https://unsplash.com/?utm_source=smart-auto-featured-image&utm_medium=referral&utm_campaign=api-credit',
        icon: <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="#000000"><g id="SVGRepo_bgCarrier" strokeWidth="0"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path fill="none" d="M0 0H24V24H0z"></path> <path d="M8.5 11v5h7v-5H21v10H3V11h5.5zm7-8v5h-7V3h7z"></path> </g> </g></svg>,
        mapping: {
            src: 'urls.small',
            href: 'urls.raw',
        }
    },
    {
        value: 'pexels',
        label: 'Pexels',
        url: 'https://www.pexels.com/',
        icon: <svg viewBox="0 0 24 24" fill="#000000" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" strokeWidth="0"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fillRule="evenodd" clipRule="evenodd" d="M12 5C12.7111 5 13.3875 5.14845 14 5.41604C15.7659 6.1876 17 7.94968 17 10C17 12.0503 15.7659 13.8124 14 14.584C13.3875 14.8516 12.7111 15 12 15V19H6V5H12ZM8 7V17H10V13H12L12.0032 12.9988C13.6427 13.0303 15.0746 11.6934 15.0443 9.95469L15.0375 9.56529C15.0121 8.10183 13.7882 6.94549 12.3257 7.00299L12.0203 7.00762L12 7H8Z" ></path> </g></svg>,
        mapping: {
            src: 'urls.medium',
            href: 'urls.original',
        }
    },
    // { value: 'pixabay', label: 'Pixabay' },
];

const defaultOptions = {
    keywords: [
        "{{title}}",
        "{{category}}",
    ],
    sources: [
        "unsplash",
        // "pexels",
    ],
    options: {
        color: null,
        orientation: null,
    },
    preferredSource: "unsplash",
    autoSelectRandom: false, // or range [0, 10] for random pick (max to 30)
    // autoSelectIndex: [0], // or range [0, 10] for random pick (max to 30)
    abortIfNoResults: false,
    abortIfEmptyKeyword: false,
};

const MagicImageSettings = ( {
    options,
    className,
    isVisible,
    elementId,
    onSave,
    onClose,
    ...props } ) => {
    // const isPro = useContext( AppContext );

    const userOptions = { ...options } || {};
    const [settings, setSettings] = useState( { ...defaultOptions, ...userOptions } );


    useEffect( () => {
        const newOptions = { ...options } || {};
        setSettings( { ...defaultOptions, ...newOptions } );
    }, [elementId] );

    const getStyles = ( () => {
        return {
            display: isVisible ? "flex" : "none",
        };
    } )();

    const insertDynamicText = ( dynText, index ) => {
        //newvalue
        const newKeywords = [...settings.keywords];
        newKeywords[index] = dynText;
        const dataChanged = {
            keywords: newKeywords
        };

        setSettings( { ...settings, ...dataChanged } );
    }

    const makeKeywordLabel = ( index ) => {
        if ( index === 0 ) return "Primary keyword";
        else if ( index === 1 ) return "Fallback keyword";
        return `Keyword ${index + 1}`;
    }

    return (
        <div className="safi-cover-bg" style={getStyles}>
            <div
                id="magic-image-settings"
                className={`safi-modal-window relative ${className || ""}`}

            >
                {/* Container */}
                <div className="safi-magic-image-container flex flex-col h-full">
                    {/* HEader */}
                    <div className="safi-magic-image-settings--header relative flex justify-center items-center px-5">
                        {__( "MagicImage will automatically search and use relevant images based on your keywords.", "wpjoli-safi" )}
                        {/* <div className="safi-close " onClick={onClose}>
                    <Icon icon="close"  />
                </div> */}
                        <div className="close-btn flex-center" onClick={onClose} style={{
                            top: '50%',
                            right: '10px',
                            transform: 'translateY(-50%)',
                        }}>
                            <div className="close-symbol"></div>
                        </div>

                    </div>

                    <div className="flex flex-1 gap-4 py-4 px-5 overflow-y-auto --safi-scroll-thin">
                        {/* Auto-search Settings */}
                        <div className="safi-magic-image-settings--container flex-1">
                            <h2>Auto-search settings</h2>
                            <Panel name="Keywords" tooltip={__( "The primary keyword will be used to search images. If no results are found, the fallback keyword will be used.", "wpjoli-safi" )} header={true} isOpen={true}>
                                <div className="flex flex-col gap-4" >
                                    {
                                        settings.keywords.map( ( keyword, index ) => (
                                            <div className="safi-prop flex flex-col" key={index}>
                                                <label htmlFor={`keyword-${index}`}>
                                                    {makeKeywordLabel( index )}
                                                </label>
                                                <DynamicText value={keyword} onTextSelected={( value ) => insertDynamicText( value, index )} >
                                                    <input
                                                        type="text"
                                                        autocomplete="off"
                                                        className="safi-plain w-full"
                                                        name="prop-text-content"
                                                        id={`keyword-${index}`}
                                                        placeholder="My text"
                                                        value={keyword}
                                                        onChange={( e ) => {
                                                            const newKeywords = [...settings.keywords];
                                                            newKeywords[index] = e.target.value;
                                                            setSettings( { ...settings, keywords: newKeywords } );
                                                        }}
                                                    />
                                                </DynamicText>
                                                {/* <SafiInput
                                                    key={index}
                                                    value={keyword}
                                                    onChange={( e ) => {
                                                        const newKeywords = [...settings.keywords];
                                                        newKeywords[index] = e.target.value;
                                                        setSettings( { ...settings, keywords: newKeywords } );
                                                    }}
                                                /> */}
                                            </div>
                                        ) )
                                    }
                                </div>
                            </Panel>
                            <Panel name="Sources" tooltip={__( "The sources to search images. Select one or multiple sources.", "wpjoli-safi" )} header={true} isOpen={true}>
                                <div className="py-2">
                                    {/* Unsplash */}
                                    <div className="safi-image-gallery-source flex gap-2">
                                        <MandatoryCheckboxGroup
                                            direction="horizontal"
                                            options={sources}
                                            selectedValues={settings.sources}
                                            onChange={( values ) => {
                                                setSettings( { ...settings, sources: values } );
                                            }}
                                        />
                                    </div>
                                </div>
                            </Panel>
                            {/* Color */}
                            <Panel name="Color" tooltip={__( "The color tone of the images. This may restrict the search results.", "wpjoli-safi" )} header={true} isOpen={false}>
                                <div className="py-2">
                                    <SimpleColorPicker
                                        color={settings.options.color}
                                        onColorChange={( color ) => {
                                            setSettings( { ...settings, options: { ...settings.options, color } } );
                                        }}
                                    />
                                </div>
                            </Panel>

                            {/* Orientation */}
                            <Panel header={true} tooltip={__( "Restrict search results to a specific orientation.", "wpjoli-safi" )} name="Orientation" isOpen={false}>
                                <div className="py-2">
                                    <div className="safi-image-gallery-orientation flex gap-2">
                                        <TextRadioGroup
                                            options={[
                                                // { value: 'all', label: 'All' },
                                                { value: 'landscape', label: 'Landscape' },
                                                { value: 'portrait', label: 'Portrait' },
                                                { value: 'square', label: 'Square' },
                                            ]}
                                            value={settings.options.orientation}
                                            onChange={( value ) => {
                                                setSettings( { ...settings, options: { ...settings.options, orientation: value } } );
                                            }}
                                        />

                                    </div>
                                </div>
                            </Panel>
                        </div>
                        {/* Auto-search Settings */}
                        <div className="safi-magic-image-settings--container flex-1">
                            <h2>Auto-select settings</h2>
                            {/* <Panel name="Prefered source" header={true} isOpen={true}>
                                {settings.sources && settings.sources.map( ( source, index ) => (
                                    <div className="safi-image-gallery-source flex gap-2" key={index}>
                                        <TextRadioGroup
                                            options={settings.sources}
                                            value={settings.preferredSource}
                                            onChange={( value ) => {
                                                setSettings( { ...settings, preferredSource: value } );
                                            }}
                                        />
                                    </div>
                                ) )}
                            </Panel> */}
                            {/* Auto-select random */}
                            <Panel name="Random pick" tooltip={__( "By default the first result is selected. Activate the option below to select a random image from the results.", "wpjoli-safi" )} header={true} isOpen={true}>
                                <div className="py-2">
                                    <SafiSwitch
                                        label="Pick a random image"
                                        title={"Pick a random image from the search results."}
                                        checked={settings.autoSelectRandom}
                                        onChange={( value ) => {
                                            setSettings( { ...settings, autoSelectRandom: value } );
                                        }}
                                    />
                                </div>
                            </Panel>
                            {/* Abort if no results */}
                            <Panel name="Image generation handling" header={true} isOpen={true}>
                                <div className="py-2">
                                    <SafiSwitch
                                        label="Abort if no results"
                                        title={"Abort the whole image generation if no results are found."}
                                        checked={settings.abortIfNoResults}
                                        onChange={( value ) => {
                                            setSettings( { ...settings, abortIfNoResults: value } );
                                        }}
                                    />
                                </div>
                            </Panel>
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="flex justify-end py-4 px-5">
                        <button
                            className="safi-tb-btn safi-btn-primary safi-btn-md"
                            onClick={() => onSave( settings )}
                        >Save</button>
                    </div>
                </div>

                {/* Auto-select settings */}

            </div>
        </div>
    );
};

export default MagicImageSettings;