/**
 * External dependencies.
 */
import { useState, useEffect } from '@wordpress/element';
import { ChartBarIcon, ArrowPathIcon, LightBulbIcon, ClockIcon, DocumentDuplicateIcon, ExclamationCircleIcon, PhotoIcon } from '@heroicons/react/24/outline';

/**
 * Internal dependencies.
 */
import Layout from '../layout/Layout';
import { fetchSiteAnalysis, deleteFile } from '../../api/size-analyzer';
import { showPromiseToast, showSuccessToast, showErrorToast } from '../../utils';

const SiteAnalyzer = () => {
    const [analyzing, setAnalyzing] = useState(false);
    const [analysisData, setAnalysisData] = useState(null);
    const [error, setError] = useState(null);
    const [activeTab, setActiveTab] = useState('overview');
    const [smartSuggestions, setSmartSuggestions] = useState([]);
    const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(false);
    const [lastRefreshTime, setLastRefreshTime] = useState(null);

    const loadAnalysisData = async () => {
        setAnalyzing(true);
        setError(null);

        try {
            const promise = fetchSiteAnalysis({
                includeFileTypes: true,
                includeLargestFiles: true,
                includeDuplicateMedia: true,
                includeDiskHistory: true,
                includeHostingQuota: false,  // Temporarily disable
                includeImageOptimization: false  // Temporarily disable
            });
            
            showPromiseToast(
                promise,
                'Analyzing site size...',
                'Analysis complete!',
                'Failed to analyze site size.'
            );

            const data = await promise;
            setAnalysisData(data);
            setLastRefreshTime(new Date());
            
            // Generate smart suggestions based on the analysis data
            generateSmartSuggestions(data);
        } catch (err) {
            console.error('Error analyzing site size:', err);
            setError('Failed to analyze site size. Please try again.');
        } finally {
            setAnalyzing(false);
        }
    };
    
    /**
     * Generate smart optimization suggestions based on analysis data
     * 
     * @param {Object} data The analysis data
     */
    const generateSmartSuggestions = (data) => {
        const suggestions = [];
        
        // Check for large uploads folder
        if (data.uploads && data.total) {
            const uploadsPercentage = (data.uploads.bytes / data.total.bytes) * 100;
            if (uploadsPercentage > 40) {
                suggestions.push({
                    id: 'large-uploads',
                    icon: '🖼️',
                    message: `Uploads folder is very large (${data.uploads.formatted}) — consider using image compression.`,
                    priority: 'high'
                });
            }
        }
        
        // Check for large plugins size
        if (data.plugins && data.total) {
            const pluginsPercentage = (data.plugins.bytes / data.total.bytes) * 100;
            if (pluginsPercentage > 25) {
                suggestions.push({
                    id: 'large-plugins',
                    icon: '🔌',
                    message: `You have ${data.plugins.formatted} of plugins. Consider removing unused ones to improve performance.`,
                    priority: 'medium'
                });
            }
        }
        
        // Check for large archive files
        if (data.file_types && data.file_types.archives) {
            const archiveSize = data.file_types.archives.size_bytes;
            if (archiveSize > 100 * 1024 * 1024) { // 100MB
                suggestions.push({
                    id: 'large-archives',
                    icon: '🗄️',
                    message: `You have ${data.file_types.archives.size_formatted} of archive files. Do you need to keep these ZIP/RAR files?`,
                    priority: 'medium'
                });
            }
        }
        
        // Check for large media files
        if (data.file_types && data.file_types.video) {
            const videoSize = data.file_types.video.size_bytes;
            if (videoSize > 200 * 1024 * 1024) { // 200MB
                suggestions.push({
                    id: 'large-videos',
                    icon: '🎬',
                    message: `You have ${data.file_types.video.size_formatted} of video files. Consider hosting videos externally on YouTube or Vimeo.`,
                    priority: 'high'
                });
            }
        }
        
        // Check for large image files
        if (data.file_types && data.file_types.images) {
            const imageCount = data.file_types.images.count;
            const imageSize = data.file_types.images.size_bytes;
            if (imageCount > 100 && imageSize > 50 * 1024 * 1024) { // 50MB
                suggestions.push({
                    id: 'many-images',
                    icon: '🖼️',
                    message: `You have ${imageCount.toLocaleString()} images using ${data.file_types.images.size_formatted}. Consider using WebP format and image optimization.`,
                    priority: 'medium'
                });
            }
        }
        
        // Check if there are extremely large individual files
        if (data.largest_files && data.largest_files.length > 0) {
            const largeFiles = data.largest_files.filter(file => file.size_bytes > 50 * 1024 * 1024); // 50MB
            if (largeFiles.length > 0) {
                suggestions.push({
                    id: 'extremely-large-files',
                    icon: '📦',
                    message: `You have ${largeFiles.length} files larger than 50MB. Review these large files in the Largest Files tab.`,
                    priority: 'high'
                });
            }
        }
        
        // Check database size
        if (data.database && data.database.bytes > 100 * 1024 * 1024) { // 100MB
            suggestions.push({
                id: 'large-database',
                icon: '🗃️',
                message: `Your database is quite large (${data.database.formatted}). Consider cleaning up post revisions, transients, and spam comments.`,
                priority: 'medium'
            });
        }
        
        // Sort suggestions by priority
        const priorityOrder = { 'high': 0, 'medium': 1, 'low': 2 };
        suggestions.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);
        
        setSmartSuggestions(suggestions);
    };
    
    const handleDeleteFile = async (filePath) => {
        if (!confirm(`Are you sure you want to delete this file? This action cannot be undone.`)) {
            return;
        }
        
        try {
            const promise = deleteFile(filePath);
            
            showPromiseToast(
                promise,
                'Deleting file...',
                'File deleted successfully!',
                'Failed to delete file.'
            );
            
            await promise;
            
            // Refresh analysis data after deletion
            loadAnalysisData();
        } catch (err) {
            console.error('Error deleting file:', err);
        }
    };

    useEffect(() => {
        loadAnalysisData();
        
        // Set up auto-refresh interval if enabled
        let intervalId;
        if (autoRefreshEnabled) {
            intervalId = setInterval(() => {
                loadAnalysisData();
            }, 15 * 60 * 1000); // Refresh every 15 minutes
        }
        
        return () => {
            if (intervalId) {
                clearInterval(intervalId);
            }
        };
    }, [autoRefreshEnabled]);

    // Calculate percentage of total for each component
    const calculatePercentage = (bytes, total) => {
        if (!total) return 0;
        return ((bytes / total) * 100).toFixed(1);
    };

    // Get color class based on percentage
    const getColorClass = (percentage) => {
        if (percentage > 50) return 'bg-red-500';
        if (percentage > 30) return 'bg-amber-500';
        if (percentage > 15) return 'bg-yellow-400';
        return 'bg-green-500';
    };
    
    // Get color indicator emoji based on percentage
    const getColorIndicator = (percentage) => {
        if (percentage > 50) return '🟥';
        if (percentage > 30) return '🟧';
        if (percentage > 15) return '🟨';
        return '🟩';
    };
    
    // Get file type indicator
    const getFileTypeIndicator = (type) => {
        switch(type) {
            case 'images': return '🖼️';
            case 'documents': return '📄';
            case 'archives': return '🗄️';
            case 'audio': return '🔊';
            case 'video': return '🎬';
            case 'code': return '📝';
            case 'fonts': return '🔤';
            default: return '📦';
        }
    };

    return (
        <Layout>
            <div className="bg-white rounded-lg shadow p-6">
                <div className="flex justify-between items-center mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">Site Size Analyzer</h1>
                        <p className="text-gray-600 mt-1">Analyze what's taking up space on your WordPress site</p>
                    </div>
                    <button
                        onClick={loadAnalysisData}
                        disabled={analyzing}
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-gray-800 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 disabled:opacity-50"
                    >
                        <ArrowPathIcon className={`-ml-1 mr-2 h-5 w-5 ${analyzing ? 'animate-spin' : ''}`} />
                        {analyzing ? 'Analyzing...' : 'Refresh Analysis'}
                    </button>
                </div>

                {error && (
                    <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
                        <div className="flex">
                            <div className="flex-shrink-0">
                                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                </svg>
                            </div>
                            <div className="ml-3">
                                <p className="text-sm text-red-700">{error}</p>
                            </div>
                        </div>
                    </div>
                )}

                {analyzing && !analysisData && (
                    <div className="flex justify-center items-center py-12">
                        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900"></div>
                    </div>
                )}

                {analysisData && (
                    <div className="space-y-8">
                        {/* Tabs Navigation */}
                        <div className="border-b border-gray-200">
                            <nav className="-mb-px flex space-x-8" aria-label="Tabs">
                                <button
                                    onClick={() => setActiveTab('overview')}
                                    className={`${activeTab === 'overview' ? 'border-gray-800 text-gray-800' : '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`}
                                >
                                    Total Site Size
                                </button>
                                <button
                                    onClick={() => setActiveTab('fileTypes')}
                                    className={`${activeTab === 'fileTypes' ? 'border-gray-800 text-gray-800' : '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`}
                                >
                                    File Type Breakdown
                                </button>
                                <button
                                    onClick={() => setActiveTab('largestFiles')}
                                    className={`${activeTab === 'largestFiles' ? 'border-gray-800 text-gray-800' : '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`}
                                >
                                    Largest Files
                                </button>
                                <button
                                    onClick={() => setActiveTab('duplicateMedia')}
                                    className={`${activeTab === 'duplicateMedia' ? 'border-gray-800 text-gray-800' : '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 flex items-center`}
                                >
                                    <DocumentDuplicateIcon className="h-4 w-4 mr-1" />
                                    Duplicate Media
                                </button>
                                <button
                                    onClick={() => setActiveTab('diskMonitor')}
                                    className={`${activeTab === 'diskMonitor' ? 'border-gray-800 text-gray-800' : '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 flex items-center`}
                                >
                                    <ClockIcon className="h-4 w-4 mr-1" />
                                    Disk Monitor
                                </button>
                                <button
                                    onClick={() => setActiveTab('imageOptimization')}
                                    className={`${activeTab === 'imageOptimization' ? 'border-gray-800 text-gray-800' : '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 flex items-center`}
                                >
                                    <PhotoIcon className="h-4 w-4 mr-1" />
                                    Image Optimization
                                </button>
                            </nav>
                        </div>

                        {/* Overview Tab Content */}
                        {activeTab === 'overview' && (
                            <div className="space-y-6">
                                <div className="bg-gray-50 p-6 rounded-lg">
                                    <div className="flex items-center justify-between mb-4">
                                        <h2 className="text-lg font-semibold text-gray-900">Total Site Size</h2>
                                        <span className="text-2xl font-bold text-gray-900">{analysisData.total.formatted}</span>
                                    </div>
                                    <p className="text-gray-600 mb-6">Breakdown of what's using space on your WordPress site</p>
                            
                            <div className="space-y-4">
                                {/* Uploads Size */}
                                <div>
                                    <div className="flex justify-between mb-1">
                                        <div className="flex items-center">
                                            <ChartBarIcon className="h-5 w-5 text-gray-500 mr-2" />
                                            <span className="text-sm font-medium text-gray-700">Media Uploads</span>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-sm font-medium text-gray-900">
                                                {analysisData.uploads.formatted} ({calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes)}%)
                                            </span>
                                        </div>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div 
                                            className={`${getColorClass(calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes))} h-2.5 rounded-full`} 
                                            style={{ width: `${calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes)}%` }}
                                        ></div>
                                    </div>
                                    <div className="mt-1 text-xs text-gray-500">
                                        {getColorIndicator(calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes))}
                                        {calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes) > 50 ? ' High usage' : calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes) > 30 ? ' Moderate usage' : ' Good'}
                                    </div>
                                </div>

                                {/* Plugins Size */}
                                <div>
                                    <div className="flex justify-between mb-1">
                                        <div className="flex items-center">
                                            <ChartBarIcon className="h-5 w-5 text-gray-500 mr-2" />
                                            <span className="text-sm font-medium text-gray-700">Plugins</span>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-sm font-medium text-gray-900">
                                                {analysisData.plugins.formatted} ({calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes)}%)
                                            </span>
                                        </div>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div 
                                            className={`${getColorClass(calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes))} h-2.5 rounded-full`} 
                                            style={{ width: `${calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes)}%` }}
                                        ></div>
                                    </div>
                                    <div className="mt-1 text-xs text-gray-500">
                                        {getColorIndicator(calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes))}
                                        {calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes) > 50 ? ' High usage' : calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes) > 30 ? ' Moderate usage' : ' Good'}
                                    </div>
                                </div>

                                {/* Themes Size */}
                                <div>
                                    <div className="flex justify-between mb-1">
                                        <div className="flex items-center">
                                            <ChartBarIcon className="h-5 w-5 text-gray-500 mr-2" />
                                            <span className="text-sm font-medium text-gray-700">Themes</span>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-sm font-medium text-gray-900">
                                                {analysisData.themes.formatted} ({calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes)}%)
                                            </span>
                                        </div>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div 
                                            className={`${getColorClass(calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes))} h-2.5 rounded-full`} 
                                            style={{ width: `${calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes)}%` }}
                                        ></div>
                                    </div>
                                    <div className="mt-1 text-xs text-gray-500">
                                        {getColorIndicator(calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes))}
                                        {calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes) > 50 ? ' High usage' : calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes) > 30 ? ' Moderate usage' : ' Good'}
                                    </div>
                                </div>

                                {/* Database Size */}
                                <div>
                                    <div className="flex justify-between mb-1">
                                        <div className="flex items-center">
                                            <ChartBarIcon className="h-5 w-5 text-gray-500 mr-2" />
                                            <span className="text-sm font-medium text-gray-700">Database</span>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-sm font-medium text-gray-900">
                                                {analysisData.database.formatted} ({calculatePercentage(analysisData.database.bytes, analysisData.total.bytes)}%)
                                            </span>
                                        </div>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div 
                                            className={`${getColorClass(calculatePercentage(analysisData.database.bytes, analysisData.total.bytes))} h-2.5 rounded-full`} 
                                            style={{ width: `${calculatePercentage(analysisData.database.bytes, analysisData.total.bytes)}%` }}
                                        ></div>
                                    </div>
                                    <div className="mt-1 text-xs text-gray-500">
                                        {getColorIndicator(calculatePercentage(analysisData.database.bytes, analysisData.total.bytes))}
                                        {calculatePercentage(analysisData.database.bytes, analysisData.total.bytes) > 50 ? ' High usage' : calculatePercentage(analysisData.database.bytes, analysisData.total.bytes) > 30 ? ' Moderate usage' : ' Good'}
                                    </div>
                                </div>

                                {/* WordPress Core Size */}
                                <div>
                                    <div className="flex justify-between mb-1">
                                        <div className="flex items-center">
                                            <ChartBarIcon className="h-5 w-5 text-gray-500 mr-2" />
                                            <span className="text-sm font-medium text-gray-700">WordPress Core</span>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-sm font-medium text-gray-900">
                                                {analysisData.wordpress.formatted} ({calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes)}%)
                                            </span>
                                        </div>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                                        <div 
                                            className={`${getColorClass(calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes))} h-2.5 rounded-full`} 
                                            style={{ width: `${calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes)}%` }}
                                        ></div>
                                    </div>
                                    <div className="mt-1 text-xs text-gray-500">
                                        {getColorIndicator(calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes))}
                                        {calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes) > 50 ? ' High usage' : calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes) > 30 ? ' Moderate usage' : ' Good'}
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Summary Table */}
                        <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                            <table className="min-w-full divide-y divide-gray-300">
                                <thead className="bg-gray-50">
                                    <tr>
                                        <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">Component</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Size</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Percentage</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200 bg-white">
                                    <tr>
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">Media Uploads</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{analysisData.uploads.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{calculatePercentage(analysisData.uploads.bytes, analysisData.total.bytes)}%</td>
                                    </tr>
                                    <tr>
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">Plugins</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{analysisData.plugins.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{calculatePercentage(analysisData.plugins.bytes, analysisData.total.bytes)}%</td>
                                    </tr>
                                    <tr>
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">Themes</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{analysisData.themes.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{calculatePercentage(analysisData.themes.bytes, analysisData.total.bytes)}%</td>
                                    </tr>
                                    <tr>
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">Database</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{analysisData.database.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{calculatePercentage(analysisData.database.bytes, analysisData.total.bytes)}%</td>
                                    </tr>
                                    <tr>
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">WordPress Core</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{analysisData.wordpress.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{calculatePercentage(analysisData.wordpress.bytes, analysisData.total.bytes)}%</td>
                                    </tr>
                                    <tr className="bg-gray-50">
                                        <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">Total</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm font-bold text-gray-900">{analysisData.total.formatted}</td>
                                        <td className="whitespace-nowrap px-3 py-4 text-sm font-bold text-gray-900">100%</td>
                                    </tr>
                                </tbody>
                            </table>
                                </div>
                            </div>
                        )}

                        {/* File Type Breakdown Tab Content */}
                        {activeTab === 'fileTypes' && analysisData.file_types && (
                            <div className="bg-white rounded-lg shadow overflow-hidden">
                                <div className="px-6 py-4 border-b border-gray-200">
                                    <h3 className="text-lg font-semibold text-gray-900">File Type Size Breakdown</h3>
                                    <p className="text-sm text-gray-600 mt-1">Size consumed by different file types across your site</p>
                                </div>
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-200">
                                        <thead className="bg-gray-50">
                                            <tr>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">File Type</th>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Count</th>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total Size</th>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Percentage</th>
                                            </tr>
                                        </thead>
                                        <tbody className="bg-white divide-y divide-gray-200">
                                            {Object.entries(analysisData.file_types)
                                                .sort((a, b) => b[1].size_bytes - a[1].size_bytes) // Sort by size descending
                                                .map(([type, data], index) => (
                                                    <tr key={type} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 capitalize">
                                                            <span className="mr-2">{getFileTypeIndicator(type)}</span>
                                                            {type}
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{data.count.toLocaleString()}</td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{data.size_formatted}</td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                            <span className="mr-2">
                                                                {getColorIndicator(((data.size_bytes / analysisData.total.bytes) * 100))}
                                                            </span>
                                                            {((data.size_bytes / analysisData.total.bytes) * 100).toFixed(1)}%
                                                        </td>
                                                    </tr>
                                                ))
                                            }
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        )}

                        {/* Largest Files Tab Content */}
                        {activeTab === 'largestFiles' && analysisData.largest_files && analysisData.largest_files.length > 0 && (
                            <div className="bg-white rounded-lg shadow overflow-hidden">
                                <div className="px-6 py-4 border-b border-gray-200">
                                    <h3 className="text-lg font-semibold text-gray-900">Largest Files</h3>
                                    <p className="text-sm text-gray-600 mt-1">The largest files on your WordPress site</p>
                                </div>
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-200">
                                        <thead className="bg-gray-50">
                                            <tr>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">File</th>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Size</th>
                                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Modified</th>
                                            </tr>
                                        </thead>
                                        <tbody className="bg-white divide-y divide-gray-200">
                                            {analysisData.largest_files.map((file, index) => (
                                                <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                                                    <td className="px-6 py-4 text-sm font-medium text-gray-900">
                                                        <div className="max-w-md truncate">
                                                            <span className="mr-2">
                                                                {getColorIndicator(((file.size_bytes / analysisData.total.bytes) * 100))}
                                                            </span>
                                                            {file.path}
                                                        </div>
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{file.size_formatted}</td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{file.modified}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        )}

                        {/* Duplicate Media Tab Content */}
                        {activeTab === 'duplicateMedia' && analysisData && analysisData.duplicate_files && (
                            <div className="space-y-6">
                                <div className="bg-white rounded-lg shadow overflow-hidden">
                                    <div className="px-6 py-4 border-b border-gray-200">
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <h3 className="text-lg font-semibold text-gray-900">🧹 Duplicate Media Files</h3>
                                                <p className="text-sm text-gray-600 mt-1">Files with identical content but different names or locations</p>
                                            </div>
                                            <div className="text-right">
                                                <div className="text-lg font-bold text-red-600">
                                                    {analysisData.duplicate_files.total_wasted_formatted} wasted
                                                </div>
                                                <div className="text-sm text-gray-500">
                                                    {analysisData.duplicate_files.total_duplicates} duplicate files in {analysisData.duplicate_files.total_groups} groups
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    {analysisData.duplicate_files.groups.length > 0 ? (
                                        <div className="divide-y divide-gray-200">
                                            {analysisData.duplicate_files.groups.map((group, groupIndex) => (
                                                <div key={groupIndex} className="p-4">
                                                    <div className="flex justify-between items-center mb-2">
                                                        <div className="font-medium text-gray-900">
                                                            Group #{groupIndex + 1}: {group.count} identical files
                                                        </div>
                                                        <div className="text-red-600 font-medium">
                                                            {group.wasted_formatted} wasted
                                                        </div>
                                                    </div>
                                                    <div className="bg-gray-50 rounded-md p-3">
                                                        <div className="text-sm text-gray-500 mb-2">These files have identical content:</div>
                                                        <ul className="space-y-1 text-sm">
                                                            {group.files.map((file, fileIndex) => (
                                                                <li key={fileIndex} className="flex items-center">
                                                                    <span className="text-gray-400 mr-2">{fileIndex + 1}.</span>
                                                                    <span className="text-gray-800 truncate">{file.path}</span>
                                                                    <span className="text-gray-500 ml-auto">{file.size_formatted}</span>
                                                                </li>
                                                            ))}
                                                        </ul>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    ) : (
                                        <div className="p-6 text-center text-gray-500">
                                            No duplicate media files found. Great job keeping your site optimized!
                                        </div>
                                    )}
                                </div>
                                
                                <div className="bg-blue-50 p-4 rounded-lg">
                                    <h4 className="font-medium text-blue-800 mb-2">Why this matters:</h4>
                                    <ul className="text-sm text-blue-700 space-y-1 list-disc pl-5">
                                        <li>Duplicate media files waste disk space and can slow down backups</li>
                                        <li>Often created when multiple editors upload the same image</li>
                                        <li>Can occur when plugins create copies of images in different folders</li>
                                        <li>Consider using a media library management plugin to prevent duplicates</li>
                                    </ul>
                                </div>
                            </div>
                        )}
                        
                        {/* Disk Monitor Tab Content */}
                        {activeTab === 'diskMonitor' && analysisData && analysisData.disk_usage_history && (
                            <div className="space-y-6">
                                <div className="bg-white rounded-lg shadow overflow-hidden">
                                    <div className="px-6 py-4 border-b border-gray-200">
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <h3 className="text-lg font-semibold text-gray-900">⚡ Realtime Disk Usage Monitor</h3>
                                                <p className="text-sm text-gray-600 mt-1">Track how your site's disk usage changes over time</p>
                                            </div>
                                            <div className="flex items-center">
                                                <div className="mr-4">
                                                    <label className="inline-flex items-center cursor-pointer">
                                                        <input 
                                                            type="checkbox" 
                                                            className="sr-only peer" 
                                                            checked={autoRefreshEnabled}
                                                            onChange={() => setAutoRefreshEnabled(!autoRefreshEnabled)}
                                                        />
                                                        <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                                        <span className="ml-2 text-sm font-medium text-gray-700">Auto-refresh</span>
                                                    </label>
                                                </div>
                                                <div className="text-right">
                                                    <div className="text-sm text-gray-500">
                                                        Last updated: {lastRefreshTime ? new Date(lastRefreshTime).toLocaleTimeString() : 'Never'}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div className="p-6">
                                        <h4 className="font-medium text-gray-900 mb-4">Disk Usage Growth</h4>
                                        
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                                            {Object.entries(analysisData.disk_usage_history.growth).map(([interval, data]) => {
                                                // Determine alert styling
                                                let alertClass = 'bg-green-50 border-green-400';
                                                let textClass = 'text-green-800';
                                                let icon = null;
                                                
                                                if (data.is_growth) {
                                                    if (data.alert_level === 'high') {
                                                        alertClass = 'bg-red-50 border-red-400';
                                                        textClass = 'text-red-800';
                                                        icon = <ExclamationCircleIcon className="h-5 w-5 text-red-500 mr-1.5" />;
                                                    } else if (data.alert_level === 'medium') {
                                                        alertClass = 'bg-amber-50 border-amber-400';
                                                        textClass = 'text-amber-800';
                                                        icon = <ExclamationCircleIcon className="h-5 w-5 text-amber-500 mr-1.5" />;
                                                    } else if (data.alert_level === 'low') {
                                                        alertClass = 'bg-yellow-50 border-yellow-400';
                                                        textClass = 'text-yellow-800';
                                                    }
                                                }
                                                
                                                return (
                                                    <div key={interval} className={`border-l-4 ${alertClass} p-4 rounded-r-md`}>
                                                        <div className="flex items-center">
                                                            {icon}
                                                            <h5 className={`font-medium ${textClass} capitalize`}>{interval}</h5>
                                                        </div>
                                                        <div className={`text-2xl font-bold ${textClass} mt-1`}>
                                                            {data.is_growth ? '+' : ''}{data.formatted}
                                                        </div>
                                                        <div className={`text-sm ${textClass}`}>
                                                            {data.is_growth ? 'Growth' : 'Reduction'} of {Math.abs(data.percentage)}%
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                        
                                        <div className="bg-gray-50 p-4 rounded-md">
                                            <h5 className="font-medium text-gray-700 mb-2">Historical Data Points</h5>
                                            <div className="overflow-x-auto">
                                                <table className="min-w-full divide-y divide-gray-200">
                                                    <thead>
                                                        <tr>
                                                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date & Time</th>
                                                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total Size</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody className="divide-y divide-gray-200 bg-white">
                                                        {analysisData.disk_usage_history.data_points.slice().reverse().map((point, index) => (
                                                            <tr key={index}>
                                                                <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-500">{point.date}</td>
                                                                <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-900">{point.size_formatted}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div className="bg-blue-50 p-4 rounded-lg">
                                    <h4 className="font-medium text-blue-800 mb-2">Why this matters:</h4>
                                    <ul className="text-sm text-blue-700 space-y-1 list-disc pl-5">
                                        <li>Sudden large increases may indicate log files growing, attack attempts, or plugin issues</li>
                                        <li>Regular small increases are normal as content is added to your site</li>
                                        <li>Enable auto-refresh to monitor changes throughout the day</li>
                                        <li>Red alerts indicate unusually rapid growth that should be investigated</li>
                                    </ul>
                                </div>
                            </div>
                        )}
                        
                        {/* Image Optimization Report Tab Content */}
                        {activeTab === 'imageOptimization' && (
                            <div className="space-y-6">
                                <div className="bg-white rounded-lg shadow overflow-hidden">
                                    <div className="px-6 py-4 border-b border-gray-200">
                                        <div className="flex items-center justify-between">
                                            <div>
                                                <h3 className="text-lg font-semibold text-gray-900">🧊 Image Optimization Report</h3>
                                                <p className="text-sm text-gray-600 mt-1">Identify opportunities to optimize your media library</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div className="p-6 text-center">
                                        <div className="bg-blue-50 p-4 rounded-md mb-4">
                                            <p className="text-blue-700">
                                                <strong>Note:</strong> The Image Optimization feature is temporarily disabled while we improve its performance. 
                                                Please check back soon for this feature.
                                            </p>
                                        </div>
                                        
                                        <p className="text-gray-500 mt-4">
                                            This feature will scan your media library for:
                                        </p>
                                        <ul className="text-gray-600 mt-2 space-y-1 list-disc list-inside text-left max-w-md mx-auto">
                                            <li>Uncompressed images</li>
                                            <li>Very large image files (over 1MB)</li>
                                            <li>CMYK or BMP images (non-web-friendly formats)</li>
                                        </ul>
                                    </div>
                                </div>
                                
                                <div className="bg-blue-50 p-4 rounded-lg">
                                    <h4 className="font-medium text-blue-800 mb-2">Recommended Optimization Tools:</h4>
                                    <ul className="text-sm text-blue-700 space-y-1 list-disc pl-5">
                                        <li><strong>ShortPixel</strong> - Excellent WordPress plugin for bulk optimization</li>
                                        <li><strong>TinyPNG</strong> - Free web service for compressing PNG and JPEG files</li>
                                        <li><strong>Imagify</strong> - WordPress plugin with great compression algorithms</li>
                                        <li><strong>EWWW Image Optimizer</strong> - Free WordPress plugin with good results</li>
                                    </ul>
                                </div>
                            </div>
                        )}
                        
                        {/* Smart Optimization Suggestions - Show in all tabs */}
                        <div className="bg-yellow-50 p-6 rounded-lg mb-6">
                            <div className="flex items-center mb-4">
                                <LightBulbIcon className="h-6 w-6 text-yellow-500 mr-2" />
                                <h3 className="text-lg font-semibold text-yellow-800">🧠 Smart Optimization Suggestions</h3>
                            </div>
                            
                            {smartSuggestions.length > 0 ? (
                                <ul className="space-y-3">
                                    {smartSuggestions.map((suggestion, index) => (
                                        <li key={suggestion.id} className="flex items-start bg-white p-3 rounded-md shadow-sm border-l-4 border-yellow-400">
                                            <span className="text-2xl mr-3">{suggestion.icon}</span>
                                            <span className="text-gray-800">{suggestion.message}</span>
                                        </li>
                                    ))}
                                </ul>
                            ) : (
                                <p className="text-gray-600">No specific optimization suggestions at this time. Your site appears to be well-optimized!</p>
                            )}
                        </div>
                        
                        {/* General Tips Section - Show in all tabs */}
                        <div className="bg-blue-50 p-6 rounded-lg">
                            <h3 className="text-lg font-semibold text-blue-900 mb-3">General Optimization Tips</h3>
                            <ul className="space-y-2 text-blue-800">
                                <li className="flex items-start">
                                    <svg className="h-5 w-5 text-blue-600 mr-2 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                    <span>Use image optimization plugins to reduce media file sizes</span>
                                </li>
                                <li className="flex items-start">
                                    <svg className="h-5 w-5 text-blue-600 mr-2 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                    <span>Clean up unused plugins and themes</span>
                                </li>
                                <li className="flex items-start">
                                    <svg className="h-5 w-5 text-blue-600 mr-2 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                    <span>Regularly optimize your database with a database cleanup plugin</span>
                                </li>
                                <li className="flex items-start">
                                    <svg className="h-5 w-5 text-blue-600 mr-2 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                    <span>Consider using a CDN for media files to offload storage</span>
                                </li>
                                <li className="flex items-start">
                                    <svg className="h-5 w-5 text-blue-600 mr-2 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                    <span>Remove large unused files identified in the largest files list</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                )}
            </div>
        </Layout>
    );
};

export default SiteAnalyzer;
