import {Tooltip} from "react-tooltip";
import CreatableSelect from "react-select/creatable";
import AppContext from "../../../contexts/AppContext";
import Uploader from "./Uploader";
import {showProModal} from "../../../includes/functions";
import {arrayMoveImmutable} from "array-move";
import {SortableContainer, SortableElement} from "react-sortable-hoc";


const {useState, useContext, useEffect} = React;

const {
    __experimentalRadioGroup: RadioGroup,
    __experimentalRadio: Radio,
} = wp.components;


const openUploader = (e, onSelect) => {
    e.preventDefault();

    // Create the media frame.
    const file_frame = wp.media.frames.file_frame = wp.media({
        title: wp.i18n.__('Select File', 'radio-player'),
        library: {
            type: 'audio',
        },
        button: {
            text: wp.i18n.__('Select', 'radio-player'),
        },
        multiple: false
    });

    file_frame.on('select', () => {

        const attachment = file_frame.state().get('selection').first().toJSON();

        onSelect(attachment.url);
    });

    // Finally, open the modal
    file_frame.open();
}

const SortableItem = SortableElement(({
                                          length,
                                          skin,
                                          value,
                                          keyIndex,
                                          options,
                                          isActive,
                                          handleActive,
                                          handleChange,
                                          handleCreate,
                                          onRemove
                                      }) => {

    const isProxyPlayerActivated = !!radioPlayer.can_proxy_player_addon;

    const httpPlayer = isProxyPlayerActivated && !!radioPlayer.settings.httpPlayer;

    const isHTTP = location.protocol === 'http:';

    const {title, stream, thumbnail, source_type = 'stream', playlist = []} = value;

    const httpWarning = (
        <div className="notice-wrap notice-warning">
            <i className="notice-icon dashicons dashicons-warning"></i>
            <div className="notice-content">
                <p>{wp.i18n.__('It appears you\'re using an HTTP stream URL, which may not play on sites loaded via HTTPS.', 'radio-player')}</p>

                {!!isProxyPlayerActivated && !httpPlayer && <p>Enable the HTTP proxy option on the <a
                    href={`${radioPlayer.admin_url}/admin.php?page=radio-player-settings&tab=proxy`}>Settings</a> page.
                </p>}

                {!isProxyPlayerActivated &&
                    <p>To play HTTP streams on HTTPS sites, install the <a target={`_blank`} href="https://softlabbd.com/radio-player-proxy/">Radio Player Proxy Add-on</a>.</p>}
            </div>
        </div>
    );

    const plsWarning = (
        <div className="notice-wrap notice-warning">
            <i className="notice-icon dashicons dashicons-warning"></i>
            <div className="notice-content">
                <p>{wp.i18n.__('Sorry, it looks like the provided URL is a .pls file. In order to play the radio station, please use the direct stream URL instead of the .pls file.', 'radio-player')}</p>
                <p>{wp.i18n.__('The direct stream URL should be something like:', 'radio-player')} <a
                    href={stream.replace(/\/(listen)?\.pls/, '/;')}
                    target={'_blank'}>{stream.replace(/\/(listen)?\.pls/, '/;')}</a>
                </p>
            </div>
        </div>
    );

    return (
        <div className={`station-item ${isActive ? 'active' : ''}`}>

            <div className="station-item-header">

                {/*--- Drag Handle ---*/}
                {length > 1 &&
                    <svg className="drag-file-item sort-item" width="24" height="24" xmlns="http://www.w3.org/2000/svg"
                         viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                        <path
                            d="M8 7h2V5H8v2zm0 6h2v-2H8v2zm0 6h2v-2H8v2zm6-14v2h2V5h-2zm0 8h2v-2h-2v2zm0 6h2v-2h-2v2z"></path>
                    </svg>
                }

                <h4 className={`item-header-title`} onClick={handleActive}>{keyIndex + 1}. {title}</h4>

                {/*---Delete Station---*/}
                {length > 1 &&
                    <button type={"button"} className={'button button-link-delete'}
                            onClick={() => {
                                Swal.fire({
                                    title: wp.i18n.__('Are you sure?', 'radio-player'),
                                    text: wp.i18n.__('Would you like to delete this station?', 'radio-player'),
                                    icon: 'warning',
                                    showCancelButton: true,
                                    confirmButtonColor: '#40CE87',
                                    cancelButtonColor: '#FF8000',
                                    confirmButtonText: wp.i18n.__('Yes, delete it!', 'radio-player'),
                                    reverseButtons: true,
                                }).then((result) => {
                                    if (result.value) {
                                        onRemove(keyIndex);
                                    }
                                });
                            }}>
                        <i className="dashicons dashicons-trash"></i>
                    </button>
                }

                {/*---Collapse Toggle Station---*/}
                <button type={"button"}
                        className={'button button-primary'}
                        onClick={handleActive}
                >
                    <i className={`dashicons ${isActive ? 'dashicons-arrow-up-alt2' : 'dashicons-arrow-down-alt2'}`}></i>
                </button>

            </div>

            {isActive &&
                <div className="station-item-body">

                    {/*--- Station Title ---*/}
                    <div className="form-group">
                        <span className={'form-label'}>{wp.i18n.__('Title', 'radio-player')}</span>

                        <div className="form-field">
                            <input type={'text'} value={title}
                                   placeholder={'Enter the station title'}
                                   onChange={(e) => handleChange({title: e.target.value})}/>

                            <p className="description">{wp.i18n.__('Enter the station title.', 'radio-player')}</p>
                        </div>

                    </div>

                    {/*--- Source ---*/}
                    <div className="form-group">
                        <h4 className={'form-label'}>{wp.i18n.__('Source', 'radio-player')}</h4>

                        <div className="form-field stream">

                            <div className="stream-type">
                                <h4 className={'form-label'}>{wp.i18n.__('Source Type', 'radio-player')}</h4>

                                <RadioGroup
                                    label={wp.i18n.__('Source Type', 'radio-player')}
                                    checked={source_type}
                                    onChange={(value) => handleChange({source_type: value})}
                                    className="source-type"
                                >
                                    <Radio value="stream">
                                        <i className="dashicons dashicons-media-audio"/>
                                        <span>{wp.i18n.__('Stream URL', 'radio-player')}</span>
                                    </Radio>
                                    <Radio value="local">
                                        <i className="dashicons dashicons-format-audio"/>
                                        <span>{wp.i18n.__('Local Audio', 'radio-player')}</span>
                                    </Radio>
                                </RadioGroup>

                                <div className="upload-input-wrap">

                                    {/* Stream url */}
                                    <input type={'url'} value={stream}
                                           placeholder={wp.i18n.__('Enter the station stream url', 'radio-player')}
                                           onChange={(e) => handleChange({stream: e.target.value})}
                                    />

                                    {/* Select media */}
                                    {source_type === 'local' &&
                                        <>
                                            <button type={'button'} className="button select-file-btn"
                                                    onClick={e => openUploader(e, (stream) => handleChange({stream}))}>
                                                <i className="dashicons dashicons-upload"> </i>
                                                <span>{wp.i18n.__('Select Local Media', 'radio-player')}</span>
                                            </button>

                                            {!!stream &&
                                                <button type={'button'} className="button remove-file-btn"
                                                        onClick={() => handleChange({stream: ''})}>
                                                    <i className="dashicons dashicons-trash"> </i>
                                                </button>
                                            }
                                        </>
                                    }

                                </div>

                                {!!stream.match(/http:/) && !httpPlayer && !isHTTP && httpWarning}

                                {!!stream.match(/\.pls/) && plsWarning}
                            </div>

                            {'stream' === source_type &&
                                <p className="description">
                                    {wp.i18n.__('Enter a playable live stream URL.', 'radio-player')}
                                    <br/>
                                    <strong>{wp.i18n.__('Example:', 'radio-player')}</strong>{' '}
                                    <a
                                        href="https://24083.live.streamtheworld.com/WBBRAMAAC.aac"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                    >
                                        https://24083.live.streamtheworld.com/WBBRAMAAC.aac
                                    </a>
                                </p>
                            }

                            {'local' === source_type &&
                                <p className="description">
                                    {wp.i18n.__('Provide a direct MP3 URL or select one from the media library.', 'radio-player')}
                                </p>
                            }

                        </div>

                    </div>

                    {/*--- Station Art ---*/}
                    <div className="form-group">
                        <span className={'form-label'}>{wp.i18n.__('Art', 'radio-player')}</span>

                        <div className="form-field">
                            <Uploader
                                media={thumbnail}
                                onChange={(media) => handleChange({thumbnail: media})}
                            />

                            <p className="description">{wp.i18n.__('Upload a station logo or image.', 'radio-player')}</p>
                        </div>
                    </div>

                    {/*--- Playlist ---*/}
                    {'skin12' === skin &&
                        <div className="form-group">
                            <span className={'form-label'}>{wp.i18n.__('Playlist', 'radio-player')}</span>

                            <div className="form-field">

                                <CreatableSelect
                                    isMulti
                                    options={options}
                                    className="radio-player-select"
                                    classNamePrefix="radio-player-select"
                                    onChange={(selected) => {
                                        handleChange({playlist: selected});
                                    }}
                                    onCreateOption={handleCreate}
                                    value={playlist}
                                    placeholder={wp.i18n.__("Select or create a playlist", "radio-player")}
                                />

                                <p className="description">{wp.i18n.__('Create a playlist or select an existing playlist.', 'radio-player')}</p>
                            </div>
                        </div>
                    }
                </div>
            }
        </div>
    )
});

const SortableList = SortableContainer(({
                                            items,
                                            skin,
                                            active,
                                            options,
                                            setActive,
                                            onRemove,
                                            handleChange,
                                            handleCreate
                                        }) => {
    return (
        <div className="radio-stations">
            {items.map((value, index) => {

                const isActive = active === index;

                return (
                    <SortableItem
                        key={index}
                        length={items.length}
                        skin={skin}
                        options={options}
                        isActive={isActive}
                        handleActive={() => setActive(isActive ? null : index)}
                        handleChange={handleChange}
                        handleCreate={handleCreate}
                        keyIndex={index}
                        index={index}
                        value={value}
                        onRemove={onRemove}
                    />
                )
            })}
        </div>
    );
});


export default function Stations() {

    const context = useContext(AppContext);

    const {editData, setEditData} = context;
    const {stations = [], skin = 'skin1'} = editData;

    // Playlist options
    const [options, setOptions] = useState([]);

    useEffect(() => {

        const initOptions = stations
            .flatMap((station) => station?.playlist || [])
            .filter(
                (item, index, self) => index === self.findIndex((t) => t.value === item.value)
            );

        setOptions(initOptions);

    }, [stations]);

    const initStation = {
        title: wp.i18n.__('Station Title', 'radio-player'),
        stream: '',
        source_type: 'stream',
        thumbnail: radioPlayer.plugin_url + '/assets/images/placeholder.png',
        playlist: [],
    }

    const [active, setActive] = useState(stations.length === 1 ? 0 : null);

    const handleChange = (obj) => {
        const key = Object.keys(obj)[0];
        const value = obj[key];


        setEditData(editData => {
            const updatedStations = [...editData.stations];
            updatedStations[active] = {
                ...updatedStations[active],
                [key]: value
            };

            return {
                ...editData,
                stations: updatedStations
            };
        });

    }

    const handleCreate = (inputValue) => {
        if (!radioPlayer.isPro) {
            showProModal();
            return;
        }

        const newOption = {label: inputValue, value: inputValue};

        setOptions((prevOptions) => [...prevOptions, newOption]);

        if (active !== null && stations[active]) {
            const currentPlaylist = stations[active].playlist || [];
            handleChange({playlist: [...currentPlaylist, newOption]});
        }
    };

    const handleDelete = (index) => {
        setEditData(data => ({...data, stations: stations.filter((item, i) => i !== index)}));
    }

    const handleAddNew = () => {
        if (!radioPlayer.isPro) {
            showProModal(wp.i18n.__('Upgrade to PRO to add multiple stations in the same player.', 'radio-player'));
            return;
        }

        // Create a deep copy of the stations array
        setEditData(data => ({...data, stations: [...stations, initStation]}));
        setActive(stations.length);
    }

    const handleSortEnd = ({oldIndex, newIndex}) => {
        setEditData(data => ({...data, stations: arrayMoveImmutable(stations, oldIndex, newIndex)}));
    }

    return (
        <div className='settings-body'>

            <div className="settings-header">
                <h3 className="settings-title">{wp.i18n.__('Radio Stations', 'radio-player')}</h3>
                <p>{wp.i18n.__('Add your radio stations here. You can add multiple radio stations with title, stream and logo.', 'radio-player')}</p>
            </div>

            <SortableList
                lockAxis={'y'}
                lockToContainerEdges={true}
                shouldCancelStart={(e) => !e.target.classList.contains('sort-item')}
                items={stations}
                skin={skin}
                active={active}
                options={options}
                setActive={setActive}
                helperClass={'sortable-item'}
                updateBeforeSortStart={() => setActive(null)}
                onSortEnd={handleSortEnd}
                handleChange={handleChange}
                handleCreate={handleCreate}
                onRemove={handleDelete}
            />

            {/* Add New Station */}
            <button type={"button"}
                    data-tooltip-content={wp.i18n.__('Multiple Stations - Pro Feature', 'radio-player')}
                    data-tooltip-id="add-new-tooltip"
                    className={`radio-player-btn btn-primary add-new-btn ${!radioPlayer.isPro ? 'disabled' : ''}`}
                    onClick={handleAddNew}>
                <i className="dashicons dashicons-plus"></i>
                <span>{wp.i18n.__('Add New Station', 'radio-player')}</span>
            </button>

            {!radioPlayer.isPro &&
                <Tooltip
                    padding="5px 10px"
                    id="add-new-tooltip"
                    place="right"
                    variant="warning"
                    effect="solid"
                />
            }

        </div>
    )

}

