import {removeAllLastFolderSessions} from "../includes/functions";
import {Tooltip} from "react-tooltip";
import {showProModal} from "../includes/ProModal";

const {useState} = React;

const SCOPES = {
    app_folder: {
        label: wp.i18n.__('Application Folder', 'integrate-google-drive'),
        desc: wp.i18n.__('A folder will be created for this plugin', 'integrate-google-drive'),
        scope: 'https://www.googleapis.com/auth/drive.file',
        icon: 'dashicons-portfolio',
        permissions: [
            {ok: true, text: wp.i18n.__('Access the plugin’s app folder', 'integrate-google-drive')},
            {ok: false, text: wp.i18n.__('No access outside this folder', 'integrate-google-drive')},
        ],
    },
    specific_folders: {
        label: wp.i18n.__('Specific Folders', 'integrate-google-drive'),
        desc: wp.i18n.__('Choose specific folders to share', 'integrate-google-drive'),
        scope: 'https://www.googleapis.com/auth/drive',
        icon: 'dashicons-category',
        permissions: [
            {ok: true, text: wp.i18n.__('Access selected folders only', 'integrate-google-drive')},
            {ok: false, text: wp.i18n.__('No access to other files', 'integrate-google-drive')},
        ],
    },
    entire_drive: {
        label: wp.i18n.__('Entire Drive', 'integrate-google-drive'),
        desc: wp.i18n.__('Full access to all files and folders', 'integrate-google-drive'),
        scope: 'https://www.googleapis.com/auth/drive',
        icon: 'dashicons-admin-site-alt3',
        permissions: [
            {ok: true, text: wp.i18n.__('Access all files and folders', 'integrate-google-drive')},
            {ok: true, text: wp.i18n.__('Manage and edit everything', 'integrate-google-drive')},
        ],
    },
};

const {isPro} = igd;

export default function Auth({width = 970, height = 850}) {
    const [value, setValue] = useState('entire_drive');
    const [showPrivacy, setShowPrivacy] = useState(false);

    const showWindow = () => {

        // Calculate the position of the new window
        const screenLeft = window.screenLeft || window.screenX;
        const screenTop = window.screenTop || window.screenY;
        const screenWidth = window.innerWidth || document.documentElement.clientWidth || screen.width;
        const screenHeight = window.innerHeight || document.documentElement.clientHeight || screen.height;

        const left = screenLeft + (screenWidth / 2) - (width / 2);
        const top = screenTop + (screenHeight / 2) - (height / 2);

        wp.ajax.post('igd_get_auth_url', {
            scope: value,
            nonce: igd.nonce,
        }).done((authUrl) => {
            removeAllLastFolderSessions();

            window.open(
                authUrl,
                'igd-auth',
                `width=${width},height=${height},left=${left},top=${top}`
            )?.focus?.();

            Swal.fire({
                title: wp.i18n.__('Almost done!', 'integrate-google-drive'),
                html: wp.i18n.__(
                    'Please follow the instructions in the newly opened window. The page will refresh automatically once authorization is complete.',
                    'integrate-google-drive'
                ),
                imageUrl: `${igd.pluginUrl}/assets/images/rocket.svg`,
                imageWidth: 64,
                imageHeight: 64,
                imageAlt: 'Google Drive',
                showCloseButton: true,
                showConfirmButton: false,
                customClass: {
                    container: 'igd-swal igd-almost-done',
                },
            });

        });
    };

    return (
        <div className="igd-auth">
            <header className="igd-auth-header">
                <h2>{wp.i18n.__('Google Drive Access', 'integrate-google-drive')}</h2>
                <p>{wp.i18n.__('Choose how this plugin can access your Drive content.', 'integrate-google-drive')}</p>
            </header>

            <div className="igd-scope-cards">
                {Object.entries(SCOPES).map(([key, option]) => {

                    const isDisabled = !isPro && (key === 'specific_folders');

                    return (
                        <div
                            key={key}
                            className={`igd-scope-card card-${key} ${value === key ? 'is-selected' : ''} ${isDisabled ? 'disabled pro-feature' : ''}`}
                            onClick={() => {
                                if (isDisabled) {
                                    showProModal(wp.i18n.__('Selecting specific folders is a PRO feature. Please upgrade to PRO to access this option.', 'integrate-google-drive'));
                                    return;
                                }

                                setValue(key);
                            }}
                        >

                            <div className="igd-card-icon">
                                <span className={`dashicons ${option.icon}`}/>
                            </div>

                            <div className="igd-card-body">
                                <strong>{option.label}</strong>
                                <p>{option.desc}</p>

                                <div className="igd-auth-permissions">
                                    {option.permissions.map((p, i) => (
                                        <div key={i} className="permission-item">
                                            <i className={`dashicons ${p.ok ? 'dashicons-saved' : 'dashicons-no-alt'}`}/>
                                            <span>{p.text}</span>
                                        </div>
                                    ))}
                                </div>

                                <details className="igd-auth-scope">
                                    <summary
                                        onClick={(e) => e.stopPropagation()}
                                    >
                                        {wp.i18n.__('Required API scope', 'integrate-google-drive')}
                                    </summary>
                                    <code title={option.scope}>{option.scope}</code>
                                </details>
                            </div>

                            {value === key && (
                                <span className="igd-check">
                                <span className="dashicons dashicons-saved"/>
                            </span>
                            )}

                            {isDisabled &&
                                <>
                                    <div
                                        className="pro-badge"
                                        data-tooltip-content={wp.i18n.__('Available in PRO', 'integrate-google-drive')}
                                        data-tooltip-id={`integration-pro-tooltip-${key}`}
                                    >
                                        <i className="igd-icon icon-pro"></i>
                                        <span className="pro-label">{wp.i18n.__('PRO', 'integrate-google-drive')}</span>
                                    </div>

                                    <Tooltip
                                        className={"igd-tooltip"}
                                        place="top"
                                        variant="warning"
                                        effect="solid"
                                        id={`integration-pro-tooltip-${key}`}
                                    />
                                </>
                            }

                        </div>
                    )
                })}


            </div>

            <footer className="igd-auth-footer">
                <div className="privacy-text-wrap">
                    <div className="privacy-text-btn" onClick={() => setShowPrivacy(!showPrivacy)}>

                        <img src={`${igd.pluginUrl}/assets/images/settings/privacy.svg`} alt="Privacy"/>

                        <span>{wp.i18n.__("See what happens with your data when you authorize?", "integrate-google-drive")}</span>
                        <i className="dashicons dashicons-arrow-down-alt2"></i>
                    </div>

                    {showPrivacy && (
                        <div className="privacy-text">
                            <p>
                                {wp.i18n.__('Authorization allows this plugin to interact with Google Drive based on the selected access level. Access tokens are stored securely on your server and are never shared with third parties. You can revoke access at any time from your Google Account settings. You can revoke access anytime from your Google Account settings or change the access level by re-authorizing the account.', 'integrate-google-drive')}
                            </p>
                        </div>
                    )}
                </div>

                <button className="igd-btn btn-outline-link" onClick={showWindow}>
                    <img src={`${igd.pluginUrl}/assets/images/google-icon.png`} alt="" width={20} height={20}/>
                    {wp.i18n.__('Continue with Google', 'integrate-google-drive')}
                </button>

            </footer>
        </div>
    );
}


export function openAddAccountWindow(width = '970', height = '850') {

    Swal.fire({
        html: '<div id="igd-auth"></div>',
        focusConfirm: false,
        showCloseButton: true,
        showConfirmButton: false,
        customClass: {
            container: 'igd-swal igd-scope-modal',
        },
        didOpen() {
            const element = document.getElementById('igd-auth');
            const root = ReactDOM.createRoot(element);
            root.render(<Auth width={width} height={height}/>);
        },

        willClose() {
            const element = document.getElementById('igd-auth');
            const root = ReactDOM.createRoot(element);
            root.unmount();
        }
    });

}