import Body from "./Selections/Body";
import Sidebar from "./Selections/Sidebar";
import List from "./Selections/List";
import {ProofingProvider} from "../contexts/ProofingContext";

const {useState, useEffect} = React;

const {Button} = wp.components;

export default function Selections() {

    const moduleId = new URLSearchParams(window.location.search).get('module_id');
    const selectionId = new URLSearchParams(window.location.search).get('selection_id');

    const [selections, setSelections] = useState(igd.selections || []);
    const [selectedTags, setSelectedTags] = useState([]);
    const [filterModule, setFilterModule] = useState(moduleId);
    const [loading, setLoading] = useState(false);

    const [submission, setSubmission] = useState(null);

    // Fetch selections on mount
    useEffect(() => {
        if (selectionId) {
            const selectedSubmission = selections.find(sel => sel.id == selectionId);
            setSubmission(selectedSubmission);
        }
    }, []);

    const exportSubmissions = (ids = []) => {
        const submissions = ids.length
            ? selections.filter(sel => ids.includes(sel.id))
            : selections;

        if (!Array.isArray(submissions) || !submissions.length) return;

        const headers = [
            'Submission ID',
            'Module ID',
            'User ID',
            'User Name',
            'User Email',
            'Message',
            'Time',
            'File ID',
            'File Name',
            'File Description',
            'Tag',
            'File URL',
        ];

        const escapeCSV = (value = '') =>
            `"${String(value).replace(/\n/g, ' ').replace(/"/g, '""')}"`;

        const rows = [];

        submissions.forEach(selection => {
            const {
                user = {},
                id,
                shortcode_id,
                message = '',
                files = [],
                created_at,
            } = selection;

            if (!files.length) {
                // Still output submission row even if no files exist
                rows.push([
                    escapeCSV(id),
                    escapeCSV(shortcode_id),
                    escapeCSV(user.id || ''),
                    escapeCSV(user.name || ''),
                    escapeCSV(user.email || ''),
                    escapeCSV(message),
                    escapeCSV(created_at),
                    '', '', '', '', '',
                ]);
                return;
            }

            files.forEach((file, index) => {
                rows.push([
                    index === 0 ? escapeCSV(id) : '',
                    index === 0 ? escapeCSV(shortcode_id) : '',
                    index === 0 ? escapeCSV(user.id || '') : '',
                    index === 0 ? escapeCSV(user.name || '') : '',
                    index === 0 ? escapeCSV(user.email || '') : '',
                    index === 0 ? escapeCSV(message) : '',
                    index === 0 ? escapeCSV(created_at) : '',

                    escapeCSV(file.id || ''),
                    escapeCSV(file.name || ''),
                    escapeCSV(file.description || ''),
                    escapeCSV(file.reviewTag?.label || ''),
                    escapeCSV(file.webViewLink || ''),
                ]);
            });
        });

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

        const a = document.createElement('a');
        a.href = url;
        a.download = `proof-submissions-${Date.now()}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

        URL.revokeObjectURL(url);
    };


    const deleteSubmissions = (ids) => {

        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_proof_submissions', {nonce: igd.nonce, ids})
        }).then(result => {
            if (result.isConfirmed) {

                setSelections(prevSelections => prevSelections.filter(item => !ids.includes(item.id)));
                setSubmission(null);

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

    // on submission change, status to read
    useEffect(() => {
        if (submission && !parseInt(submission.status)) {
            wp.ajax
                .post('igd_mark_selection_as_read', {
                    nonce: igd.nonce,
                    id: submission.id
                })
                .done(() => {
                    setSelections(prevSelections => prevSelections.map(sel => sel.id === submission.id ? {
                        ...sel,
                        status: 1
                    } : sel));
                })
                .fail(error => console.error('Error marking selection as read:', error));
        }
    }, [submission]);

    return (
        <ProofingProvider
            value={{
                selections,
                setSelections,
                selectedTags,
                setSelectedTags,
                submission,
                setSubmission,
                loading,
                setLoading,
                filterModule,
                setFilterModule,
                deleteSubmissions,
                exportSubmissions,
            }}
        >
            <div className="igd-proof-selections">

                {/* Header */}
                <div className="igd-proof-selections-header">

                    <div className="header-title-wrap">

                        <div className="header-icon"
                             onClick={() => setSubmission(null)}
                        >
                            <img src={`${igd.pluginUrl}/assets/images/shortcode-builder/types/review-alt.svg`}/>
                        </div>

                        <div className={'header-title'}>
                            <h2>{wp.i18n.__('Proofing Submissions', 'integrate-google-drive')}</h2>
                            <p>{wp.i18n.__('View and manage files selected by users for review and approval.', 'integrate-google-drive')}</p>
                        </div>

                    </div>

                    <div className="header-actions">

                        {!submission &&
                            <>
                                <Button
                                    className="igd-btn btn-info"
                                    href={`https://softlabbd.com/docs/how-to-enable-google-drive-photo-and-file-proofing/`}
                                    label={wp.i18n.__('Learn how proofing works', 'integrate-google-drive')}
                                    text={wp.i18n.__('Documentation', 'integrate-google-drive')}
                                    target="_blank"
                                    icon="info-outline"
                                />

                                {!igd.isPro &&
                                    <Button
                                        href={`https://softlabbd.com/integrate-google-drive-pricing`}
                                        className={`igd-btn btn-outline-primary`}
                                        target={"_blank"}
                                        label={wp.i18n.__('Unlock PRO', 'integrate-google-drive')}
                                        text={wp.i18n.__('Get PRO', 'integrate-google-drive')}
                                        icon="info-outline"
                                    />
                                }
                            </>
                        }

                        {submission &&
                            <>
                                <Button
                                    className="igd-btn delete-selection"
                                    icon="trash"
                                    label={wp.i18n.__('Delete Selection', 'integrate-google-drive')}
                                    text={wp.i18n.__('Delete', 'integrate-google-drive')}
                                    onClick={() => deleteSubmissions([submission.id])}
                                />

                                <Button
                                    className="igd-btn download-selection"
                                    icon="download"
                                    label={wp.i18n.__('Download as CSV', 'integrate-google-drive')}
                                    text={wp.i18n.__('Download CSV', 'integrate-google-drive')}
                                    onClick={() => exportSubmissions([submission.id])}
                                />

                                <Button
                                    className="igd-btn back-btn"
                                    icon="arrow-left"
                                    label={wp.i18n.__('Back to Selections', 'integrate-google-drive')}
                                    text={wp.i18n.__('Back', 'integrate-google-drive')}
                                    onClick={() => {
                                        setSubmission(null);
                                        const url = new URL(window.location);
                                        url.searchParams.delete('selection_id');
                                        window.history.pushState({}, '', url);
                                    }}
                                />
                            </>
                        }

                    </div>

                </div>

                {loading && <div className="igd-spinner spinner-large"></div>}

                {/* List */}
                {!loading && !submission && <List/>}

                {/* Content */}
                {!loading && submission &&
                    <div className="igd-proof-selections-content">

                        {/*--- Sidebar ---*/}
                        <Sidebar/>

                        {/* Body */}
                        <Body/>

                    </div>
                }

            </div>
        </ProofingProvider>
    );
}
