import {loadAvatar, md5} from "../../includes/functions";
import ProofingContext from "../../contexts/ProofingContext";

const {useContext} = React;
const {Button} = wp.components;

export default function Sidebar() {

    const context = useContext(ProofingContext);

    const {
        setSelections,
        selectedTags = [],
        setSelectedTags,
        submission = {},
    } = context;

    const downloadSelectionAsCSV = (selection) => {
        const {user = {}, id, shortcode_id, message = '', files = [], created_at} = selection;

        const headers = [
            'Selection ID', 'Shortcode ID', 'User ID', 'User Name', 'User Email', 'Message', 'Date',
            'File ID', 'File Name', 'File Description', 'Tag', 'File URL'
        ];

        const rows = files.map((file, i) => [
            i === 0 ? id : '',
            i === 0 ? `"${shortcode_id}"` : '',
            i === 0 ? `"${user.id || ''}"` : '',
            i === 0 ? `"${user.name || ''}"` : '',
            i === 0 ? `"${user.email || ''}"` : '',
            i === 0 ? `"${message.replace(/\n/g, ' ').replace(/"/g, '""')}"` : '',
            i === 0 ? `"${created_at}"` : '',

            `"${file.id || ''}"`,
            `"${file.name || ''}"`,
            `"${file.description || ''}"`,
            `"${file.reviewTag?.label || ''}"`,
            `"${file.webViewLink || ''}"`,
        ]);

        const blob = new Blob([[headers, ...rows].map(r => r.join(',')).join('\n')], {type: 'text/csv'});
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = `selection-${id}.csv`;
        a.click();

        URL.revokeObjectURL(url);
    };

    const confirmAndDeleteSelection = (id) => {
        Swal.fire({
            title: wp.i18n.__('Are you sure?', 'integrate-google-drive'),
            text: wp.i18n.__('You won\'t be able to revert this!', 'integrate-google-drive'),
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: wp.i18n.__('Yes, delete it!', 'integrate-google-drive'),
            reverseButtons: true,
            showLoaderOnConfirm: true,
            customClass: {container: 'igd-swal igd-swal-reverse'},
            preConfirm: () => wp.ajax.post('igd_delete_selection', {nonce: igd.nonce, id})
        }).then(result => {
            if (result.isConfirmed) {

                setSelections(prev => prev.filter(s => s.id !== id));

                Swal.fire({
                    title: wp.i18n.__('Deleted!', 'integrate-google-drive'),
                    text: wp.i18n.__('Selection has been deleted.', 'integrate-google-drive'),
                    icon: 'success',
                    showConfirmButton: false,
                    timer: 1500,
                    toast: true,
                    customClass: {container: 'igd-swal'},
                });
            }
        });
    };

    const {user = {}, message, module, created_at, updated_at, page = '', files = []} = submission;
    const isUpdated = updated_at && created_at && new Date(updated_at) > new Date(created_at);

    // Unique tags with counts
    const tagCountMap = {};
    const uniqueTags = [];

    files.forEach(file => {
        const tag = file.reviewTag;

        if (tag?.value) {
            tagCountMap[tag.value] = (tagCountMap[tag.value] || 0) + 1;
            if (!uniqueTags.some(t => t.value === tag.value)) {
                uniqueTags.push(tag);
            }
        }

    });

    return (
        <div className="igd-proof-selections-sidebar">
            <div className="filter-wrap">

                <div className="filter-section">
                    <h4 className="filter-section-title">{wp.i18n.__('Submission Details:', 'integrate-google-drive')}</h4>

                    <div className="igd-selection-details">

                        <p className="detail-item">
                            <strong>{wp.i18n.__('User:', 'integrate-google-drive')}</strong><br/>

                            <Button
                                href={user.id ? `${igd.adminUrl}/user-edit.php&user_id=${user.id}` : false}
                                label={wp.i18n.__('View User', 'integrate-google-drive')}
                                text={user.name ? `${user.name} (${user.email})` : user.email || ''}
                                target="_blank"
                            />
                        </p>

                        {message &&
                            <p><strong>{wp.i18n.__('Message:', 'integrate-google-drive')}</strong><br/>{message}</p>}

                        {module &&
                            <p><strong>{wp.i18n.__('Module:', 'integrate-google-drive')}</strong><br/>
                                <Button
                                    className={`module-title-text`}
                                    href={`${igd.adminUrl}admin.php?page=integrate-google-drive-shortcode-builder&id=${module.id}`}
                                    label={wp.i18n.__('Edit Module', 'integrate-google-drive')}
                                    text={`${module.title}`}
                                />
                            </p>}

                        <p>
                            <strong>{wp.i18n.__('Created at:', 'integrate-google-drive')}</strong><br/>
                            {created_at || 'N/A'}
                        </p>

                        {isUpdated &&
                            <p><strong>{wp.i18n.__('Updated at:', 'integrate-google-drive')}</strong><br/>{updated_at}
                            </p>}

                        {page && <p>
                            <strong>{wp.i18n.__('Submission Page:', 'integrate-google-drive')}</strong><br/>
                            <a href={page} target="_blank">{page}</a>
                        </p>
                        }
                    </div>

                </div>

                {/* Tags Filter */}
                <div className="filter-section">
                    <h4 className="filter-section-title">
                        {wp.i18n.__('Filter by Tags:', 'integrate-google-drive')}

                        {/*    Clear Button */}
                        {selectedTags.length > 0 && (
                            <Button
                                className="clear-filters-btn"
                                onClick={() => setSelectedTags([])}
                                label={wp.i18n.__('Clear Filters', 'integrate-google-drive')}
                                text={wp.i18n.__('Clear', 'integrate-google-drive')}
                                icon={'no-alt'}
                            />
                        )}

                    </h4>

                    <div className="filter-section-items">
                        {uniqueTags.length ? (
                            uniqueTags.map(({value, label, color}) => (
                                <div className="filter-item" key={value}>
                                    <input
                                        type="checkbox"
                                        id={`tag-${value}`}
                                        checked={selectedTags.includes(value)}
                                        onChange={() => {
                                            if (selectedTags.includes(value)) {
                                                setSelectedTags(selectedTags.filter(t => t !== value));
                                            } else {
                                                setSelectedTags([...selectedTags, value]);
                                            }
                                        }}
                                    />

                                    <label htmlFor={`tag-${value}`} style={{color}}>
                                        <i className="dashicons dashicons-tag"/>
                                        <span className="filter-item-name">{label}</span>
                                        <span className="filter-item-count">({tagCountMap[value] || 0})</span>
                                    </label>
                                </div>
                            ))
                        ) : (
                            <div className="no-items">{wp.i18n.__('No tags available', 'integrate-google-drive')}</div>
                        )}
                    </div>
                </div>

            </div>
        </div>
    );
}
