import {Tooltip} from "react-tooltip";
import AppContext from "../../contexts/AppContext";
import {copyShortcode, formatDate, setIdParam, showProModal} from "../../includes/functions";
import Pagination from "../../includes/Pagination/Pagination";

const {FormToggle, CheckboxControl, SelectControl} = wp.components;

const {useContext, useState, useEffect} = React;

export default function List() {
    const isPro = radioPlayer.isPro;

    const context = useContext(AppContext);
    const {
        players,
        getPlayers,
        deletePlayer,
        setEdit,
        updatePlayer,
        total,
        page,
        setPage,
        perPage,
        setPerPage,
        sortBy,
        setSortBy,
        sortOrder,
        setSortOrder,
    } = context;

    const [selectedShortcode, setSelectedShortcode] = useState([]);

    const initColumns = ['ID', 'status', 'shortcode', 'date'];
    const savedColumns = localStorage.getItem('radio_player_shortcode_list_columns');

    const [columns, setColumns] = useState(savedColumns ? JSON.parse(savedColumns) : initColumns);

    useEffect(() => {
        localStorage.setItem('radio_player_shortcode_list_columns', JSON.stringify(columns));
    }, [columns]);

    const duplicatePlayer = (playerIds) => {

        playerIds.forEach((id) => {
            const item = players.find((player) => player.id === id);

            const {config, title} = item;

            updatePlayer({...config, id: '', title: `Copy of ${title}`}).then(() => {
                Swal.fire({
                    title: wp.i18n.__('Success', 'radio-player'),
                    text: wp.i18n.__('Player duplicated successfully', 'radio-player'),
                    icon: 'success',
                    toast: true,
                    timer: 2000,
                    showConfirmButton: false,
                });
            });
        });

    }

    return (
        <div className="player-list-wrap">

            <div className="player-list-header">

                <h3 className={`player-list-title`}>
                    {wp.i18n.__("All Players", "radio-player")}
                    <span
                        className="player-list-count"> ({total} {wp.i18n._n("Item", "Items", total, "radio-player")}) </span>
                </h3>

                {/* Column Settings */}
                <div className={`list-column-settings`}>
                    <i className="column-settings-icon dashicons dashicons-admin-generic"></i>

                    <Tooltip
                        anchorSelect={`.column-settings-icon`}
                        place="left"
                        variant="light"
                        clickable={true}
                        border={`1px solid #ddd`}
                        scrollHide={false}
                        className="radio-player-tooltip list-settings-tooltip"
                    >
                        {/* Column Settings */}
                        <div className="settings-wrap settings-columns">
                            <h4>{wp.i18n.__('Columns', 'radio-player')}</h4>
                            <div className="rp-checkboxes column-options">
                                {
                                    ['ID', 'status', 'shortcode', 'locations', 'date'].map((column, index) => {
                                        return (
                                            <div className="column-setting" key={index}>
                                                <CheckboxControl
                                                    label={column}
                                                    checked={columns.includes(column)}
                                                    className={`rp-checkbox`}
                                                    __nextHasNoMarginBottom={true}
                                                    onChange={() => {
                                                        const newColumns = columns.includes(column) ? columns.filter(item => item !== column) : [...columns, column];

                                                        setColumns(newColumns);
                                                    }}
                                                />
                                            </div>
                                        );
                                    })
                                }
                            </div>
                        </div>

                        {/* Items Per Page */}
                        <div className="settings-wrap settings-per-page">
                            <h4>{wp.i18n.__('Items Per Page', 'radio-player')}</h4>

                            <SelectControl
                                value={perPage}
                                options={[
                                    {label: '10', value: 10},
                                    {label: '20', value: 20},
                                    {label: '50', value: 50},
                                    {label: '100', value: 100},
                                ]}
                                onChange={value => {
                                    setPerPage(value);
                                    setPage(1);
                                    localStorage.setItem('radio_player_list_per_page', value);
                                }}
                                __next40pxDefaultSize={true}
                                __nextHasNoMarginBottom={true}

                            />
                        </div>

                        {/* Sort By */}
                        <div className="settings-wrap settings-sort-by">
                            <h4>{wp.i18n.__('Sort By', 'radio-player')}</h4>

                            <SelectControl
                                value={sortBy}
                                options={[
                                    {label: wp.i18n.__('ID', 'radio-player'), value: 'id'},
                                    {label: wp.i18n.__('Name', 'radio-player'), value: 'title'},
                                    {label: wp.i18n.__('Date Created', 'radio-player'), value: 'created_at'},
                                ]}
                                onChange={value => {
                                    setSortBy(value);
                                    setPage(1);
                                    localStorage.setItem('radio_player_list_sort_by', value);
                                }}
                                __next40pxDefaultSize={true}
                                __nextHasNoMarginBottom={true}

                            />
                        </div>

                        {/* Sort Order */}
                        <div className="settings-wrap settings-sort-order">
                            <h4>{wp.i18n.__('Sort Order', 'radio-player')}</h4>

                            <SelectControl
                                value={sortOrder}
                                options={[
                                    {label: wp.i18n.__('Ascending', 'radio-player'), value: 'asc'},
                                    {label: wp.i18n.__('Descending', 'radio-player'), value: 'desc'},
                                ]}
                                onChange={value => {
                                    setSortOrder(value);
                                    setPage(1);
                                    localStorage.setItem('radio_player_list_sort_order', value);
                                }}
                                __next40pxDefaultSize={true}
                                __nextHasNoMarginBottom={true}

                            />
                        </div>
                    </Tooltip>
                </div>
            </div>

            {/* Selection */}
            {!!selectedShortcode.length &&
                <div className="selection-actions-wrap">
                    <div className="selection-count">
                        {selectedShortcode.length} {wp.i18n.__('Item(s) selected', 'radio-player')}
                    </div>

                    <button
                        className="radio-player-btn btn-warning"
                        onClick={() => setSelectedShortcode([])}>
                        <i className={'dashicons dashicons-no-alt'}></i>
                        <span>{wp.i18n.__('Clear Selection', 'radio-player')}</span>
                    </button>

                    {/* Duplicate */}
                    <>
                        <button
                            data-tooltip-content={wp.i18n.__('PRO Feature', 'radio-player')}
                            data-tooltip-id={`duplicate-pro`}
                            className="radio-player-btn btn-info"
                            onClick={() => {

                                if (!isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to duplicate player.', 'radio-player'));
                                    return;
                                }

                                duplicatePlayer(selectedShortcode);
                                setSelectedShortcode([]);
                            }}>
                            <i className={'dashicons dashicons-admin-page'}></i>
                            <span>{wp.i18n.__('Duplicate', 'radio-player')}</span>
                        </button>

                        {!isPro && <Tooltip id={`duplicate-pro`} className={'radio-player-tooltip'} place="top"
                                            variant="warning"
                                            effect="solid"/>}
                    </>

                    {/* Delete Selection */}
                    <button
                        className="radio-player-btn btn-danger"
                        onClick={() => {

                            Swal.fire({
                                title: wp.i18n.__('Are you sure?', 'radio-player'),
                                text: wp.i18n.__('You will not be able to recover this shortcode!', 'radio-player'),
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#FF8000',
                                cancelButtonColor: '#40CE87',
                                confirmButtonText: wp.i18n.__('Yes, delete it!', 'radio-player'),
                                reverseButtons: true,
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    selectedShortcode.forEach(id => deletePlayer(id));
                                    setSelectedShortcode([]);

                                    getPlayers();
                                }
                            });
                        }}>
                        <i className={'dashicons dashicons-trash'}></i>
                        <span>{wp.i18n.__('Delete', 'radio-player')}</span>
                    </button>
                </div>
            }

            {/*---- List ---*/}
            <table className="player-list">
                <thead>
                <tr>
                    <th className={`col-selection`}>
                        <CheckboxControl
                            checked={selectedShortcode.length === players.length}
                            __nextHasNoMarginBottom={true}
                            onChange={() => {
                                if (selectedShortcode.length === players.length) {
                                    setSelectedShortcode([]);
                                } else {
                                    setSelectedShortcode(players.map(player => player.id));
                                }
                            }}
                        />

                    </th>

                    {columns.includes('ID') &&
                        <th className={`col-id`}>{wp.i18n.__("ID", 'radio-player')}</th>
                    }

                    <th className={`col-title`}>{wp.i18n.__("Title", 'radio-player')}</th>

                    {columns.includes('status') &&
                        <th className={`col-status`}>{wp.i18n.__("Status", 'radio-player')}

                            <i className={`dashicons dashicons-info col-status-info`}></i>

                            <Tooltip
                                anchorSelect={`.col-status-info`}
                                content={wp.i18n.__("Shortcode active/inactive status", 'radio-player')}
                                place="top"
                                className={"radio-player-tooltip list-th-tooltip"}
                            />
                        </th>
                    }

                    {columns.includes('shortcode') &&
                        <th className={`col-shortcode`}>{wp.i18n.__("Shortcode", 'radio-player')}</th>
                    }

                    {columns.includes('locations') &&
                        <th className={`col-date`}>
                            {wp.i18n.__("Locations", 'radio-player')}

                            <i className={`dashicons dashicons-info col-locations-info`}></i>

                            <Tooltip
                                anchorSelect={`.col-locations-info`}
                                content={wp.i18n.__("The locations where the shortcode is used", 'radio-player')}
                                place="top"
                                className={"radio-player-tooltip list-th-tooltip"}
                            />

                        </th>
                    }

                    {columns.includes('date') &&
                        <th className={`col-date`}>{wp.i18n.__("Created at", 'radio-player')}</th>
                    }

                    <th className={`col-actions`}>{wp.i18n.__("Actions", 'radio-player')}</th>
                </tr>
                </thead>

                <tbody>

                {
                    players.map(item => {

                        const {id, title, status, created_at, config, locations = []} = item;

                        return (
                            <tr className="player-list-item">

                                {/* Checkbox */}
                                <td className={`col-selection`}>
                                    <CheckboxControl
                                        checked={selectedShortcode.includes(id)}
                                        __nextHasNoMarginBottom={true}
                                        onChange={() => {
                                            if (selectedShortcode.includes(id)) {
                                                setSelectedShortcode(selectedShortcode.filter(item => item !== id));
                                            } else {
                                                setSelectedShortcode([...selectedShortcode, id]);
                                            }
                                        }}
                                    />
                                </td>

                                {/* ID */}
                                {columns.includes('ID') &&
                                    <td className={`col-id`}>{id}</td>
                                }

                                {/* Title */}
                                <td className={`col-title`}
                                    onClick={() => {
                                        setIdParam(id);
                                        setEdit(id);
                                    }}
                                >{title}</td>

                                {/* Status */}
                                {columns.includes('status') &&
                                    <td className="col-shortcode-status">

                                        <FormToggle
                                            data-tooltip-content={wp.i18n.__("Player status", 'radio-player')}
                                            data-tooltip-id="player_status"
                                            checked={status}
                                            onChange={() => updatePlayer({...config, id, status: !status})}
                                        />

                                        <Tooltip
                                            id="player_status"
                                            effect="solid"
                                            place="top"
                                        />

                                    </td>
                                }

                                {/* Shortcode */}
                                {columns.includes('shortcode') &&
                                    <td className="col-code">
                                        <div onClick={() => copyShortcode(id)}>
                                            <i className="dashicons dashicons-admin-page"></i>
                                            <code>{`[radio_player id="${id}"]`}</code>
                                        </div>
                                    </td>
                                }

                                {/* Locations */}
                                {columns.includes('locations') &&
                                    <td className="col-locations">
                                        {!!locations && locations.length > 0 ?
                                            <div className="shortcode-locations">
                                                <span
                                                    data-tooltip-id={`shortcodeLocations-${id}`}
                                                    className="location-count">{locations.length}</span>

                                                <Tooltip
                                                    id={`shortcodeLocations-${id}`}
                                                    effect="solid"
                                                    place="top"
                                                    openOnClick="click"
                                                    variant="light"
                                                    clickable={true}
                                                    border={`1px solid #ddd`}
                                                    scrollHide={false}
                                                    className="radio-player-tooltip"
                                                    globalEventOff="click"
                                                >
                                                    <h3>{wp.i18n.__('Player Locations', 'radio-player')}</h3>

                                                    {
                                                        locations.map((location, index) => {
                                                            return (
                                                                <div
                                                                    key={index}
                                                                    className="location-item">
                                                                    <a href={location.url} target="_blank">
                                                                        <span>{index + 1}. </span> {location.title}
                                                                        <i className="dashicons dashicons-external"></i>
                                                                    </a>
                                                                </div>
                                                            )
                                                        })
                                                    }
                                                </Tooltip>

                                            </div>
                                            :
                                            <div className="shortcode-locations">
                                                <span
                                                    className="location-count">{wp.i18n.__('0', 'radio-player')}</span>
                                            </div>
                                        }
                                    </td>
                                }

                                {/* Date */}
                                {columns.includes('date') &&
                                    <td className="col-date">{formatDate(created_at)}</td>
                                }

                                {/* Actions */}
                                <td className="col-actions">

                                    {/* Edit Player */}
                                    <button
                                        className="radio-player-btn"
                                        onClick={() => {
                                            setIdParam(id);
                                            setEdit(id);
                                        }}>
                                        <i className="dashicons dashicons-edit"></i>
                                        <span>{wp.i18n.__('Edit', 'radio-player')}</span>
                                    </button>

                                    {/* Tools */}
                                    <button className={`radio-player-btn btn-tools btn-${id}`}>
                                        <i className="dashicons dashicons-ellipsis"></i>
                                    </button>

                                    <Tooltip
                                        anchorSelect={`.btn-${id}`}
                                        place="bottom"
                                        variant="light"
                                        border={`1px solid #ddd`}
                                        className="radio-player-tooltip options-tooltip"
                                        clickable
                                        content={
                                            <div className="action-tools">

                                                {/*--- Edit Shortcode ---*/}
                                                <button
                                                    className="radio-player-btn"
                                                    onClick={() => {
                                                        setIdParam(id);
                                                        setEdit(id);
                                                    }}>

                                                    <i className="dashicons dashicons-edit"></i>
                                                    <span>{wp.i18n.__('Edit', 'radio-player')}</span>
                                                </button>

                                                {/*--- Preview Shortcode ---*/}
                                                <button
                                                    className="radio-player-btn"
                                                    onClick={() => {
                                                        window.open(radioPlayer.site_url + `/radio-player/${id}`, `radio_player_preview_${id}`);
                                                    }}>
                                                    <i className="dashicons dashicons-external"></i>
                                                    <span>{wp.i18n.__('View', 'radio-player')}</span>
                                                </button>

                                                {/*--- Duplicate shortcode ---*/}
                                                <>
                                                    <button
                                                        data-tooltip-content={isPro ? wp.i18n.__('Duplicate Player', 'radio-player') : wp.i18n.__('PRO Feature', 'radio-player')}
                                                        data-tooltip-id={`duplicate-tooltip-${id}`}
                                                        className="radio-player-btn"
                                                        onClick={() => {
                                                            if (!isPro) {
                                                                showProModal(wp.i18n.__('Upgrade to PRO to duplicate player.', 'radio-player'));
                                                                return;
                                                            }

                                                            duplicatePlayer([id]);
                                                        }}>
                                                        <i className="dashicons dashicons-admin-page"></i>
                                                        <span>{wp.i18n.__('Duplicate', 'radio-player')}</span>
                                                    </button>

                                                    {!isPro &&
                                                        <Tooltip
                                                            id={`duplicate-tooltip-${id}`}
                                                            className={'radio-player-tooltip'}
                                                            place="left"
                                                            variant="warning"
                                                        />
                                                    }

                                                </>

                                                {/* Embed Code */}
                                                <button
                                                    data-tooltip-content={isPro ? wp.i18n.__('Get Embed Code', 'radio-player') : wp.i18n.__('PRO Feature', 'radio-player')}
                                                    data-tooltip-id={`embed-tooltip-${id}`}
                                                    className={`radio-player-btn ${!isPro ? 'disabled' : ''}`}
                                                    onClick={() => {

                                                        if (!isPro) {
                                                            showProModal(wp.i18n.__('Upgrade to PRO to embed the player on any website or page.', 'radio-player'));
                                                            return;
                                                        }

                                                        Swal.fire({
                                                            title: wp.i18n.__('Embed Code', 'radio-player'),
                                                            html: `<p class="embed-code-title">${wp.i18n.__('Insert the following code into any webpage to showcase the player.', 'radio-player')}</p><textarea class="embed-code" rows="5" readonly>${`<iframe src="${radioPlayer.site_url}/?radio_player=${id}&embed" width="100%" height="350" frameborder="0"></iframe>`}</textarea>`,
                                                            showCloseButton: true,
                                                            showCancelButton: false,
                                                            confirmButtonText: wp.i18n.__('Copy', 'radio-player'),
                                                            confirmButtonColor: '#40CE87',
                                                            customClass: {
                                                                container: 'radio-player-swal embed-code-swal',
                                                            },
                                                            didOpen: () => {
                                                                document.querySelector('.embed-code').select();

                                                            }
                                                        }).then((result) => {
                                                            if (result.value) {
                                                                document.querySelector('.embed-code').select();
                                                                document.execCommand("copy");

                                                                Swal.fire({
                                                                    title: wp.i18n.__('Copied!', 'radio-player'),
                                                                    text: wp.i18n.__('Embed code copied to clipboard', 'radio-player'),
                                                                    icon: 'success',
                                                                    toast: true,
                                                                    showConfirmButton: false,
                                                                    timer: 3000,
                                                                    timerProgressBar: true,
                                                                });
                                                            }
                                                        });
                                                    }}>

                                                    <i className="dashicons dashicons-editor-code"></i>
                                                    <span>{wp.i18n.__('Embed Code', 'radio-player')}</span>

                                                    {!isPro && <span className="radio-player-pro-icon"><span className={`radio-player-icon icon-pro`}/></span>}

                                                </button>

                                                {!isPro &&
                                                    <Tooltip
                                                        id={`embed-tooltip-${id}`}
                                                        className={'radio-player-tooltip'}
                                                        place="left"
                                                        variant="warning"
                                                    />
                                                }

                                                {/* Delete shortcode */}
                                                <button
                                                    className="radio-player-btn btn-delete"
                                                    onClick={() => {

                                                        Swal.fire({
                                                            title: wp.i18n.__("Are you sure?", "radio-player"),
                                                            text: wp.i18n.__("You won't be able to revert this!", "radio-player"),
                                                            icon: 'warning',
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#FF8000',
                                                            cancelButtonColor: '#40CE87',
                                                            confirmButtonText: wp.i18n.__("Yes, delete it!", "radio-player"),
                                                            cancelButtonText: wp.i18n.__("No, cancel!", "radio-player"),
                                                            reverseButtons: true,
                                                            focusCancel: true,
                                                            showLoaderOnConfirm: true,
                                                            preConfirm: () => {
                                                                return deletePlayer(id);
                                                            }
                                                        });
                                                    }}>
                                                    <i className="dashicons dashicons-trash"></i>
                                                    <span>{wp.i18n.__('Delete', 'radio-player')}</span>
                                                </button>

                                            </div>
                                        }
                                    />

                                </td>
                            </tr>
                        )
                    })
                }

                </tbody>
            </table>

            {/* Pagination */}
            <div className="player-list-footer">
                <Pagination
                    className={"player-list-pagination"}
                    pageCount={Math.ceil(total / perPage)}
                    currentPage={page}
                    onPageChange={page => setPage(page)}
                />
            </div>

        </div>
    )
}