/**
 * Plugins and Themes Cleaner component.
 */
import { useState, useEffect } from '@wordpress/element';
import { TrashIcon, ArrowPathIcon, ExclamationCircleIcon, ShieldCheckIcon } from '@heroicons/react/24/outline';

/**
 * Internal dependencies.
 */
import Layout from '../layout/Layout';
import { fetchPluginsStatus, fetchThemesStatus, bulkDelete } from '../../api/plugins-themes-cleaner';
import { showPromiseToast, showSuccessToast, showErrorToast } from '../../utils';
import DummyContentRemover from './DummyContentRemover';

const PluginsThemesCleaner = () => {
    const [loading, setLoading] = useState(true);
    const [plugins, setPlugins] = useState([]);
    const [themes, setThemes] = useState([]);
    const [selectedPlugins, setSelectedPlugins] = useState([]);
    const [selectedThemes, setSelectedThemes] = useState([]);
    const [activeFeatureTab, setActiveFeatureTab] = useState('plugins-themes');
    const [activeTab, setActiveTab] = useState('plugins');
    const [error, setError] = useState(null);
    const [skipWithUpdates, setSkipWithUpdates] = useState(true);
    const [skipWithDependencies, setSkipWithDependencies] = useState(true);
    const [isDeleting, setIsDeleting] = useState(false);
    const [totalSavings, setTotalSavings] = useState(0);
    const [totalSavingsFormatted, setTotalSavingsFormatted] = useState('0 B');

    // Load data
    const loadData = async () => {
        setLoading(true);
        setError(null);

        try {
            const pluginsPromise = fetchPluginsStatus();
            const themesPromise = fetchThemesStatus();
            
            showPromiseToast(
                Promise.all([pluginsPromise, themesPromise]),
                'Loading plugins and themes...',
                'Plugins and themes loaded successfully!',
                'Failed to load plugins and themes.'
            );

            const [pluginsData, themesData] = await Promise.all([pluginsPromise, themesPromise]);
            
            // Filter out active plugins and themes
            const inactivePlugins = pluginsData.filter(plugin => !plugin.is_active);
            const inactiveThemes = themesData.filter(theme => !theme.is_active && !theme.is_parent);
            
            setPlugins(inactivePlugins);
            setThemes(inactiveThemes);
        } catch (err) {
            console.error('Error loading plugins and themes:', err);
            setError('Failed to load plugins and themes. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    // Initial data load
    useEffect(() => {
        if (activeFeatureTab === 'plugins-themes') {
            loadData();
        }
    }, [activeFeatureTab]);

    // Calculate total savings whenever selection changes
    useEffect(() => {
        let total = 0;
        
        // Add selected plugins size
        selectedPlugins.forEach(pluginPath => {
            const plugin = plugins.find(p => p.path === pluginPath);
            if (plugin) {
                total += plugin.size;
            }
        });
        
        // Add selected themes size
        selectedThemes.forEach(themeSlug => {
            const theme = themes.find(t => t.slug === themeSlug);
            if (theme) {
                total += theme.size;
            }
        });
        
        setTotalSavings(total);
        setTotalSavingsFormatted(formatSize(total));
    }, [selectedPlugins, selectedThemes, plugins, themes]);

    // Toggle plugin selection
    const togglePluginSelection = (pluginPath) => {
        setSelectedPlugins(prevSelected => {
            if (prevSelected.includes(pluginPath)) {
                return prevSelected.filter(path => path !== pluginPath);
            } else {
                return [...prevSelected, pluginPath];
            }
        });
    };

    // Toggle theme selection
    const toggleThemeSelection = (themeSlug) => {
        setSelectedThemes(prevSelected => {
            if (prevSelected.includes(themeSlug)) {
                return prevSelected.filter(slug => slug !== themeSlug);
            } else {
                return [...prevSelected, themeSlug];
            }
        });
    };

    // Handle bulk delete
    const handleBulkDelete = async () => {
        if (selectedPlugins.length === 0 && selectedThemes.length === 0) {
            showErrorToast('Please select at least one plugin or theme to delete.');
            return;
        }

        if (!window.confirm('Are you sure you want to delete the selected plugins and themes? This action cannot be undone.')) {
            return;
        }

        setIsDeleting(true);

        try {
            const result = await bulkDelete({
                plugins: selectedPlugins,
                themes: selectedThemes
            });

            // Show success message
            const totalDeleted = result.plugins.success.length + result.themes.success.length;
            const totalFailed = result.plugins.failed.length + result.themes.failed.length;
            
            if (totalDeleted > 0) {
                showSuccessToast(`Successfully deleted ${totalDeleted} item${totalDeleted !== 1 ? 's' : ''}.`);
            }
            
            if (totalFailed > 0) {
                showErrorToast(`Failed to delete ${totalFailed} item${totalFailed !== 1 ? 's' : ''}.`);
            }

            // Reset selections
            setSelectedPlugins([]);
            setSelectedThemes([]);
            
            // Reload data
            loadData();
        } catch (err) {
            console.error('Error deleting items:', err);
            showErrorToast('Failed to delete selected items. Please try again.');
        } finally {
            setIsDeleting(false);
        }
    };

    // Format bytes to human-readable size
    const formatSize = (bytes, precision = 2) => {
        if (bytes === 0) return '0 B';
        
        const units = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(1024));
        
        return parseFloat((bytes / Math.pow(1024, i)).toFixed(precision)) + ' ' + units[i];
    };

    // Check if a plugin should be disabled from selection
    const isPluginDisabled = (plugin) => {
        if (skipWithUpdates && plugin.has_update) {
            return true;
        }
        
        if (skipWithDependencies && plugin.usage && plugin.usage.dependencies.length > 0) {
            return true;
        }
        
        return false;
    };

    return (
        <Layout>
            <div className="bg-white rounded-lg shadow p-6">
                <div className="mb-6">
                    <h1 className="text-2xl font-bold text-gray-900">🧹 Site Cleanup Tools</h1>
                    <p className="mt-1 text-gray-600">
                        Tools to clean up your WordPress site and improve security, performance, and organization.
                    </p>
                </div>

                {/* Feature Tabs */}
                <div className="mb-6">
                    <div className="border-b border-gray-200">
                        <nav className="-mb-px flex space-x-8" aria-label="Feature Tabs">
                            <button
                                onClick={() => setActiveFeatureTab('plugins-themes')}
                                className={`${
                                    activeFeatureTab === 'plugins-themes'
                                        ? 'border-blue-500 text-blue-600'
                                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                                } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                            >
                                Inactive Plugins & Themes
                            </button>
                            <button
                                onClick={() => setActiveFeatureTab('dummy-content')}
                                className={`${
                                    activeFeatureTab === 'dummy-content'
                                        ? 'border-blue-500 text-blue-600'
                                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                                } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                            >
                                Dummy Content Remover
                            </button>
                        </nav>
                    </div>
                </div>

                {/* Plugins & Themes Cleaner */}
                {activeFeatureTab === 'plugins-themes' && (
                    <>
                        {error && (
                            <div className="mb-6 bg-red-50 border-l-4 border-red-400 p-4">
                                <div className="flex">
                                    <div className="flex-shrink-0">
                                        <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                                    </div>
                                    <div className="ml-3">
                                        <p className="text-sm text-red-700">{error}</p>
                                    </div>
                                </div>
                            </div>
                        )}

                        <div className="mb-4 flex justify-between items-center">
                            <div className="space-x-2">
                                <button
                                    onClick={loadData}
                                    disabled={loading}
                                    className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                >
                                    <ArrowPathIcon className={`-ml-0.5 mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
                                    Refresh
                                </button>
                            </div>

                            <div className="text-right">
                                {(selectedPlugins.length > 0 || selectedThemes.length > 0) && (
                                    <div className="text-sm text-gray-600 mb-2">
                                        Selected: {selectedPlugins.length + selectedThemes.length} items ({totalSavingsFormatted})
                                    </div>
                                )}
                                <button
                                    onClick={handleBulkDelete}
                                    disabled={isDeleting || (selectedPlugins.length === 0 && selectedThemes.length === 0)}
                                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                    <TrashIcon className="-ml-1 mr-2 h-5 w-5" />
                                    {isDeleting ? 'Deleting...' : 'Delete Selected'}
                                </button>
                            </div>
                        </div>

                        <div className="mb-6">
                            <div className="border-b border-gray-200">
                                <nav className="-mb-px flex" aria-label="Tabs">
                                    <button
                                        onClick={() => setActiveTab('plugins')}
                                        className={`${
                                            activeTab === 'plugins'
                                                ? 'border-blue-500 text-blue-600'
                                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                                        } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                                    >
                                        Inactive Plugins ({plugins.length})
                                    </button>
                                    <button
                                        onClick={() => setActiveTab('themes')}
                                        className={`${
                                            activeTab === 'themes'
                                                ? 'border-blue-500 text-blue-600'
                                                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                                        } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ml-8`}
                                    >
                                        Unused Themes ({themes.length})
                                    </button>
                                </nav>
                            </div>
                        </div>

                        <div className="mb-4 flex items-center space-x-6">
                            <div className="flex items-center">
                                <input
                                    id="skip-updates"
                                    type="checkbox"
                                    checked={skipWithUpdates}
                                    onChange={() => setSkipWithUpdates(!skipWithUpdates)}
                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                />
                                <label htmlFor="skip-updates" className="ml-2 block text-sm text-gray-700">
                                    Skip plugins with updates
                                </label>
                            </div>
                            <div className="flex items-center">
                                <input
                                    id="skip-dependencies"
                                    type="checkbox"
                                    checked={skipWithDependencies}
                                    onChange={() => setSkipWithDependencies(!skipWithDependencies)}
                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                />
                                <label htmlFor="skip-dependencies" className="ml-2 block text-sm text-gray-700">
                                    Skip plugins with dependencies
                                </label>
                            </div>
                        </div>

                        {loading ? (
                            <div className="text-center py-12">
                                <div className="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
                                <p className="mt-2 text-gray-600">Loading...</p>
                            </div>
                        ) : (
                            <>
                                {/* Plugins Tab */}
                                {activeTab === 'plugins' && (
                                    <div className="bg-white shadow overflow-hidden sm:rounded-md">
                                        {plugins.length === 0 ? (
                                            <div className="px-4 py-5 sm:p-6 text-center">
                                                <ShieldCheckIcon className="mx-auto h-12 w-12 text-green-500" />
                                                <h3 className="mt-2 text-sm font-medium text-gray-900">No inactive plugins found</h3>
                                                <p className="mt-1 text-sm text-gray-500">
                                                    Great job! Your WordPress installation doesn't have any inactive plugins.
                                                </p>
                                            </div>
                                        ) : (
                                            <ul className="divide-y divide-gray-200">
                                                {plugins.map((plugin) => {
                                                    const isDisabled = isPluginDisabled(plugin);
                                                    const hasWarning = plugin.usage && plugin.usage.dependencies.length > 0;
                                                    
                                                    return (
                                                        <li key={plugin.path}>
                                                            <div className="px-4 py-4 sm:px-6">
                                                                <div className="flex items-center justify-between">
                                                                    <div className="flex items-center">
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={selectedPlugins.includes(plugin.path)}
                                                                            onChange={() => togglePluginSelection(plugin.path)}
                                                                            disabled={isDisabled}
                                                                            className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                                        />
                                                                        <div className="ml-3">
                                                                            <h3 className="text-sm font-medium text-gray-900">{plugin.name}</h3>
                                                                            <div className="mt-1 flex items-center">
                                                                                <span className="text-xs text-gray-500">
                                                                                    Version: {plugin.version} | Size: {plugin.size_formatted}
                                                                                </span>
                                                                                {plugin.has_update && (
                                                                                    <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                                                        Update Available
                                                                                    </span>
                                                                                )}
                                                                                {hasWarning && (
                                                                                    <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                                                        Has Dependencies
                                                                                    </span>
                                                                                )}
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                {hasWarning && (
                                                                    <div className="mt-2 text-sm text-red-600">
                                                                        <ExclamationCircleIcon className="inline-block h-4 w-4 mr-1" />
                                                                        Warning: This plugin may be used by {plugin.usage.dependencies.map(dep => `${dep.count} ${dep.name}`).join(', ')}
                                                                    </div>
                                                                )}
                                                                <div className="mt-2 text-sm text-gray-500">{plugin.description}</div>
                                                            </div>
                                                        </li>
                                                    );
                                                })}
                                            </ul>
                                        )}
                                    </div>
                                )}

                                {/* Themes Tab */}
                                {activeTab === 'themes' && (
                                    <div className="bg-white shadow overflow-hidden sm:rounded-md">
                                        {themes.length === 0 ? (
                                            <div className="px-4 py-5 sm:p-6 text-center">
                                                <ShieldCheckIcon className="mx-auto h-12 w-12 text-green-500" />
                                                <h3 className="mt-2 text-sm font-medium text-gray-900">No unused themes found</h3>
                                                <p className="mt-1 text-sm text-gray-500">
                                                    Great job! Your WordPress installation doesn't have any unused themes.
                                                </p>
                                            </div>
                                        ) : (
                                            <ul className="divide-y divide-gray-200">
                                                {themes.map((theme) => (
                                                    <li key={theme.slug}>
                                                        <div className="px-4 py-4 sm:px-6">
                                                            <div className="flex items-center justify-between">
                                                                <div className="flex items-center">
                                                                    <input
                                                                        type="checkbox"
                                                                        checked={selectedThemes.includes(theme.slug)}
                                                                        onChange={() => toggleThemeSelection(theme.slug)}
                                                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                                    />
                                                                    <div className="ml-3">
                                                                        <h3 className="text-sm font-medium text-gray-900">{theme.name}</h3>
                                                                        <div className="mt-1 flex items-center">
                                                                            <span className="text-xs text-gray-500">
                                                                                Version: {theme.version} | Size: {theme.size_formatted}
                                                                            </span>
                                                                            {theme.has_update && (
                                                                                <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                                                    Update Available
                                                                                </span>
                                                                            )}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div className="mt-2 text-sm text-gray-500">{theme.description}</div>
                                                        </div>
                                                    </li>
                                                ))}
                                            </ul>
                                        )}
                                    </div>
                                )}
                            </>
                        )}

                        <div className="mt-6 bg-blue-50 p-4 rounded-md">
                            <h3 className="text-sm font-medium text-blue-800">Why this matters:</h3>
                            <ul className="mt-2 text-sm text-blue-700 list-disc pl-5 space-y-1">
                                <li>Inactive plugins and themes can pose security risks if they have vulnerabilities</li>
                                <li>They take up disk space and can make your backups larger than necessary</li>
                                <li>They add clutter to your WordPress dashboard</li>
                                <li>Regular cleanup helps maintain a healthy WordPress installation</li>
                            </ul>
                        </div>
                    </>
                )}

                {/* Dummy Content Remover */}
                {activeFeatureTab === 'dummy-content' && (
                    <DummyContentRemover />
                )}
            </div>
        </Layout>
    );
};

export default PluginsThemesCleaner;
