import {Tooltip} from "react-tooltip";
import {copyShortcode, timeAgo} from "../../includes/functions";
import Toggle from "../Toggle";

const {useEffect, useState} = React;

const {CheckboxControl,} = wp.components;

export default function List({
                                 toggles,
                                 filteredToggles,
                                 deleteToggle,
                                 duplicateToggle,
                                 setEdit,
                                 sortBy,
                                 setSortBy,
                                 sortOrder,
                                 setSortOrder,
                             }) {


    const [selectedToggles, setSelectedToggles] = useState([]);

    const initColumns = ['ID', 'title', 'preview', 'shortcode', 'created'];
    const savedColumns = localStorage.getItem('dracula_shortcode_list_columns');

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

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

    return (
        <div className="dracula-toggle-list-wrap">

            <div className="dracula-toggle-list-header">
                <h3 className="dracula-toggle-list-title">
                    {wp.i18n.__('All Toggles', 'dracula-dark-mode')}
                    <span
                        className="toggle-list-count"> ( {toggles.length} {wp.i18n._n("Item", "Items", toggles.length, "dracula-dark-mode")} )</span>
                </h3>

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

                    <Tooltip
                        id={`list-settings-tooltip`}
                        effect="solid"
                        place="left"
                        openOnClick="click"
                        variant="light"
                        clickable={true}
                        border={`1px solid #ddd`}
                        scrollHide={false}
                        className="dracula-tooltip list-settings-tooltip"
                        globalEventOff="click"
                    >

                        {/* Column Settings */}
                        <div className="settings-wrap settings-columns">
                            <h4>{wp.i18n.__('Columns', 'dracula-dark-mode')}</h4>

                            <div className="column-options">
                                {
                                    ['ID', 'preview', 'shortcode', 'created'].map((column, index) => {
                                        return (
                                            <div className="dracula-column-setting" key={index}>
                                                <CheckboxControl
                                                    label={column}
                                                    checked={columns.includes(column)}
                                                    onChange={() => {
                                                        const newColumns = columns.includes(column) ? columns.filter(item => item !== column) : [...columns, column];

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

                    </Tooltip>
                </div>

            </div>

            {!!selectedToggles.length &&
                <div className="selection-actions-wrap">
                    <div className="selection-count">
                        {selectedToggles.length} {wp.i18n.__('Item(s) selected', 'dracula-dark-mode')}
                    </div>

                    <button
                        type="button"
                        className="dracula-btn btn-warning"
                        onClick={() => setSelectedToggles([])}>
                        <i className={'dashicons dashicons-no-alt'}></i>
                        <span>{wp.i18n.__('Clear Selection', 'dracula-dark-mode')}</span>
                    </button>

                    {/* Duplicate */}
                    <button
                        type="button"
                        className="dracula-btn btn-info"
                        onClick={() => {
                            duplicateToggle(selectedToggles);

                            setSelectedToggles([]);
                        }}>
                        <i className={'dashicons dashicons-admin-page'}></i>
                        <span>{wp.i18n.__('Duplicate', 'dracula-dark-mode')}</span>
                    </button>

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

                            Swal.fire({
                                title: wp.i18n.__('Are you sure?', 'dracula-dark-mode'),
                                text: wp.i18n.__('You will not be able to recover this shortcode!', 'dracula-dark-mode'),
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonText: wp.i18n.__('Yes, delete it!', 'dracula-dark-mode'),
                                reverseButtons: true,
                                customClass: {container: 'dracula-swal'},
                            }).then((result) => {
                                if (result.isConfirmed) {

                                    selectedToggles.forEach(id => {
                                        deleteToggle(id);
                                    });

                                    setSelectedToggles([]);
                                }
                            });
                        }}>
                        <i className={'dashicons dashicons-trash'}></i>
                        <span>{wp.i18n.__('Delete', 'dracula-dark-mode')}</span>
                    </button>
                </div>
            }

            <table className="dracula-toggle-list">
                <thead>

                <tr>
                    <th className={`col-selection`}>
                        <CheckboxControl
                            checked={selectedToggles.length === toggles.length}
                            onChange={() => {
                                if (selectedToggles.length === toggles.length) {
                                    setSelectedToggles([]);
                                } else {
                                    setSelectedToggles(toggles.map(toggle => toggle.id));
                                }
                            }}
                        />
                    </th>

                    {columns.includes('ID') &&
                        <th className={'col-id'}>
                            <div
                                className={`sortable ${sortBy === 'id' && sortOrder} ${sortBy === 'id' ? 'active' : ''}`}
                                onClick={() => {
                                    setSortBy('id');
                                    setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                                }}
                            >
                                <span>{wp.i18n.__("ID", 'dracula-dark-mode')}</span>
                                <i className={`dashicons dashicons-arrow-up`}></i>
                            </div>
                        </th>
                    }

                    <th className={`col-title`}>
                        <div
                            className={`sortable ${sortBy === 'title' && sortOrder} ${sortBy === 'title' ? 'active' : ''}`}
                            onClick={() => {
                                setSortBy('title');
                                setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                            }}
                        >
                            <span>{wp.i18n.__("Title", 'dracula-dark-mode')}</span>
                            <i className={`dashicons dashicons-arrow-up`}></i>
                        </div>
                    </th>

                    {columns.includes('preview') &&
                        <th className={`col-preview`}>{wp.i18n.__("Preview", 'dracula-dark-mode')}</th>
                    }

                    {columns.includes('shortcode') &&
                        <th>{wp.i18n.__("Shortcode", 'dracula-dark-mode')}</th>
                    }

                    {columns.includes('created') &&
                        <th>
                            <div
                                className={`sortable`}
                                onClick={() => {
                                    setSortBy('id');
                                    setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                                }}
                            >
                                <span>{wp.i18n.__("Created at", 'dracula-dark-mode')}</span>
                                <i className={`dashicons dashicons-arrow-up ${sortOrder}`}></i>
                            </div>
                        </th>
                    }

                    <th>{wp.i18n.__("Actions", 'dracula-dark-mode')}</th>

                </tr>
                </thead>

                <tbody>

                {
                    filteredToggles.map(item => {

                        const {id, title, created_at, config} = item;

                        return (
                            <tr className="dracula-toggle-list-item">

                                {/* Selection */}
                                <td className={`col-selection`}>
                                    <CheckboxControl
                                        checked={selectedToggles.includes(id)}
                                        onChange={() => {
                                            if (selectedToggles.includes(id)) {
                                                setSelectedToggles(selectedToggles.filter(item => item !== id));
                                            } else {
                                                setSelectedToggles([...selectedToggles, id]);
                                            }
                                        }
                                        }
                                    />
                                </td>

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

                                {/* Preview */}
                                {columns.includes('preview') &&
                                    <th className="col-preview">
                                        <div className="dracula-toggle-wrap custom-toggle">
                                            <Toggle data={config} isPreview previewMode={'light'}/>
                                        </div>
                                    </th>
                                }

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

                                            <i data-tooltip-content={wp.i18n.__("Copy shortcode", 'dracula-dark-mode')}
                                               data-tooltip-id="copyShortcode"
                                               className="dashicons dashicons-admin-page"
                                               onClick={copyShortcode}></i>

                                            <Tooltip id="copyShortcode" effect="solid" place="left"/>

                                            <code onClick={copyShortcode}>
                                                {`[dracula_toggle id="${id}"]`}
                                            </code>
                                        </div>
                                    </td>
                                }

                                {/* Created at */}
                                {columns.includes('created') &&
                                    <td className="col-created">{timeAgo(created_at)}</td>
                                }

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

                                    {/* Delete toggle */}
                                    <button
                                        type="button"
                                        data-tooltip-content={wp.i18n.__("Delete toggle", 'dracula-dark-mode')}
                                        data-tooltip-id="deleteToggle"
                                        className="dracula-btn btn-outline-danger"
                                        onClick={() => {
                                            Swal.fire({
                                                title: wp.i18n.__("Are you sure?", "dracula-dark-mode"),
                                                text: wp.i18n.__("You won't be able to revert this!", "dracula-dark-mode"),
                                                icon: 'warning',
                                                showCancelButton: true,
                                                confirmButtonText: wp.i18n.__("Yes, delete it!", "dracula-dark-mode"),
                                                cancelButtonText: wp.i18n.__("No, cancel!", "dracula-dark-mode"),
                                                reverseButtons: true,
                                                focusCancel: true,
                                                showLoaderOnConfirm: true,
                                                customClass: {container: 'dracula-swal'},
                                                preConfirm: () => {
                                                    return deleteToggle(id);
                                                }
                                            });
                                        }}>
                                        <i className="dashicons dashicons-trash"></i>
                                    </button>

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

                                    {/* Duplicate toggle */}
                                    <button
                                        type="button"
                                        data-tooltip-content={wp.i18n.__("Duplicate toggle", 'dracula-dark-mode')}
                                        data-tooltip-id="duplicateToggle"
                                        className="dracula-btn btn-outline-info"
                                        onClick={() => {
                                            duplicateToggle([id])
                                        }}>
                                        <i className="dashicons dashicons-admin-page"></i>
                                    </button>

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

                                    {/*  Edit toggle */}
                                    <button
                                        type="button"
                                        data-tooltip-content={wp.i18n.__("Edit toggle", 'dracula-dark-mode')}
                                        data-tooltip-id="editToggle"
                                        className="dracula-btn btn-outline-primary"
                                        onClick={() => setEdit(id)}>
                                        <i className="dashicons dashicons-edit-large"></i>
                                    </button>

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

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

                </tbody>
            </table>
        </div>
    )
}