/**
 * File Tweaker component.
 */
import { useState, useEffect } from '@wordpress/element';
import { 
    DocumentTextIcon, 
    CodeBracketIcon, 
    ArrowPathIcon, 
    ExclamationCircleIcon,
    LightBulbIcon,
    ClockIcon,
    CheckCircleIcon,
    XMarkIcon
} from '@heroicons/react/24/outline';

/**
 * Internal dependencies.
 */
import Layout from '../layout/Layout';
import { 
    fetchHtaccess,
    updateHtaccess,
    fetchRobots,
    updateRobots,
    fetchHtaccessSuggestions,
    fetchRobotsSuggestions,
    fetchBackups,
    restoreBackup
} from '../../api/file-tweaker';
import { showToast } from '../../utils';

const FileTweaker = () => {
    const [activeTab, setActiveTab] = useState('htaccess');
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    
    // File content states
    const [htaccessContent, setHtaccessContent] = useState('');
    const [robotsContent, setRobotsContent] = useState('');
    const [originalHtaccessContent, setOriginalHtaccessContent] = useState('');
    const [originalRobotsContent, setOriginalRobotsContent] = useState('');
    const [htaccessInfo, setHtaccessInfo] = useState({});
    const [robotsInfo, setRobotsInfo] = useState({});
    
    // Suggestions and backups states
    const [htaccessSuggestions, setHtaccessSuggestions] = useState([]);
    const [robotsSuggestions, setRobotsSuggestions] = useState([]);
    const [htaccessBackups, setHtaccessBackups] = useState([]);
    const [robotsBackups, setRobotsBackups] = useState([]);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [showBackups, setShowBackups] = useState(false);
    
    // Load data based on active tab
    useEffect(() => {
        loadData();
    }, [activeTab]);
    
    // Load data for the current tab
    const loadData = async () => {
        setLoading(true);
        setError(null);
        
        try {
            // Load data based on active tab
            if (activeTab === 'htaccess') {
                await loadHtaccess();
                await loadHtaccessSuggestions();
                await loadHtaccessBackups();
            } else if (activeTab === 'robots') {
                await loadRobots();
                await loadRobotsSuggestions();
                await loadRobotsBackups();
            }
        } catch (err) {
            console.error(`Error loading ${activeTab} data:`, err);
            setError(`Failed to load ${activeTab} data. Please try again.`);
        } finally {
            setLoading(false);
        }
    };
    
    // Load .htaccess file content
    const loadHtaccess = async () => {
        const data = await fetchHtaccess();
        setHtaccessContent(data.content);
        setOriginalHtaccessContent(data.content);
        setHtaccessInfo({
            exists: data.exists,
            writable: data.writable,
            path: data.path
        });
    };
    
    // Load robots.txt file content
    const loadRobots = async () => {
        const data = await fetchRobots();
        setRobotsContent(data.content);
        setOriginalRobotsContent(data.content);
        setRobotsInfo({
            exists: data.exists,
            writable: data.writable,
            path: data.path
        });
    };
    
    // Load .htaccess suggestions
    const loadHtaccessSuggestions = async () => {
        const suggestions = await fetchHtaccessSuggestions();
        setHtaccessSuggestions(suggestions);
    };
    
    // Load robots.txt suggestions
    const loadRobotsSuggestions = async () => {
        const suggestions = await fetchRobotsSuggestions();
        setRobotsSuggestions(suggestions);
    };
    
    // Load .htaccess backups
    const loadHtaccessBackups = async () => {
        const backups = await fetchBackups('htaccess');
        setHtaccessBackups(backups);
    };
    
    // Load robots.txt backups
    const loadRobotsBackups = async () => {
        const backups = await fetchBackups('robots');
        setRobotsBackups(backups);
    };
    
    // Handle saving .htaccess
    const handleSaveHtaccess = async () => {
        if (!htaccessInfo.writable) {
            setError('The .htaccess file is not writable. Please check file permissions.');
            return;
        }
        
        setSaving(true);
        setError(null);
        
        try {
            const result = await updateHtaccess(htaccessContent);
            
            if (result.success) {
                showToast(result.message, 'success');
                setOriginalHtaccessContent(htaccessContent);
                await loadHtaccessBackups();
            } else {
                setError(result.message || 'Failed to update .htaccess file.');
            }
        } catch (err) {
            console.error('Error updating .htaccess:', err);
            setError('Failed to update .htaccess file. Please try again.');
        } finally {
            setSaving(false);
        }
    };
    
    // Handle saving robots.txt
    const handleSaveRobots = async () => {
        if (!robotsInfo.writable) {
            setError('The robots.txt file is not writable. Please check file permissions.');
            return;
        }
        
        setSaving(true);
        setError(null);
        
        try {
            const result = await updateRobots(robotsContent);
            
            if (result.success) {
                showToast(result.message, 'success');
                setOriginalRobotsContent(robotsContent);
                await loadRobotsBackups();
            } else {
                setError(result.message || 'Failed to update robots.txt file.');
            }
        } catch (err) {
            console.error('Error updating robots.txt:', err);
            setError('Failed to update robots.txt file. Please try again.');
        } finally {
            setSaving(false);
        }
    };
    
    // Handle restoring from backup
    const handleRestoreBackup = async (file, type) => {
        if (!window.confirm(`Are you sure you want to restore from this backup? Current changes will be lost.`)) {
            return;
        }
        
        setLoading(true);
        setError(null);
        
        try {
            const result = await restoreBackup(file, type);
            
            if (result.success) {
                showToast(result.message, 'success');
                
                if (type === 'htaccess') {
                    setHtaccessContent(result.content);
                    setOriginalHtaccessContent(result.content);
                    await loadHtaccessBackups();
                } else {
                    setRobotsContent(result.content);
                    setOriginalRobotsContent(result.content);
                    await loadRobotsBackups();
                }
            } else {
                setError(result.message || `Failed to restore from backup.`);
            }
        } catch (err) {
            console.error('Error restoring from backup:', err);
            setError('Failed to restore from backup. Please try again.');
        } finally {
            setLoading(false);
        }
    };
    
    // Handle applying a suggestion
    const handleApplySuggestion = (suggestion) => {
        if (activeTab === 'htaccess') {
            // Append the suggestion to the current content
            const newContent = htaccessContent + '\n\n' + suggestion.code;
            setHtaccessContent(newContent);
        } else {
            // Append the suggestion to the current content
            const newContent = robotsContent + '\n\n' + suggestion.code;
            setRobotsContent(newContent);
        }
        
        // Close suggestions panel
        setShowSuggestions(false);
    };
    
    // Check if content has been modified
    const isContentModified = () => {
        if (activeTab === 'htaccess') {
            return htaccessContent !== originalHtaccessContent;
        } else {
            return robotsContent !== originalRobotsContent;
        }
    };
    
    // Handle discarding changes
    const handleDiscardChanges = () => {
        if (!window.confirm('Are you sure you want to discard your changes?')) {
            return;
        }
        
        if (activeTab === 'htaccess') {
            setHtaccessContent(originalHtaccessContent);
        } else {
            setRobotsContent(originalRobotsContent);
        }
    };
    
    return (
        <Layout>
            <div className="bg-white rounded-lg shadow p-6">
                <div className="mb-6">
                    <h1 className="text-2xl font-bold text-gray-900">⚙️ Fast .htaccess & Robots.txt Tweaker</h1>
                    <p className="mt-1 text-gray-600">
                        Safely edit critical files with smart suggestions and automatic backups.
                    </p>
                </div>
                
                {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>
                )}
                
                {/* Tabs */}
                <div className="mb-6">
                    <div className="border-b border-gray-200">
                        <nav className="-mb-px flex space-x-8" aria-label="Tabs">
                            <button
                                onClick={() => setActiveTab('htaccess')}
                                className={`${
                                    activeTab === 'htaccess'
                                        ? '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 flex items-center`}
                            >
                                <CodeBracketIcon className="h-5 w-5 mr-2" />
                                .htaccess Editor
                            </button>
                            <button
                                onClick={() => setActiveTab('robots')}
                                className={`${
                                    activeTab === 'robots'
                                        ? '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 flex items-center`}
                            >
                                <DocumentTextIcon className="h-5 w-5 mr-2" />
                                robots.txt Editor
                            </button>
                        </nav>
                    </div>
                </div>
                
                {/* Refresh Button */}
                <div className="mb-4 flex justify-between">
                    <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 className="flex space-x-2">
                        <button
                            onClick={() => setShowSuggestions(!showSuggestions)}
                            className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-amber-700 bg-white hover:bg-amber-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-amber-500"
                        >
                            <LightBulbIcon className="h-4 w-4 mr-2" />
                            {showSuggestions ? 'Hide Suggestions' : 'Show Suggestions'}
                        </button>
                        
                        <button
                            onClick={() => setShowBackups(!showBackups)}
                            className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-indigo-700 bg-white hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        >
                            <ClockIcon className="h-4 w-4 mr-2" />
                            {showBackups ? 'Hide Backups' : 'Show Backups'}
                        </button>
                    </div>
                </div>
                
                {/* Main Content */}
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* Editor Column */}
                    <div className={`lg:col-span-${showSuggestions || showBackups ? '2' : '3'}`}>
                        {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>
                        ) : (
                            <div>
                                {/* File Info */}
                                <div className="mb-4 bg-gray-50 p-3 rounded-md text-sm">
                                    <p>
                                        <span className="font-medium">File:</span>{' '}
                                        {activeTab === 'htaccess' ? htaccessInfo.path : robotsInfo.path}
                                    </p>
                                    <p>
                                        <span className="font-medium">Status:</span>{' '}
                                        {activeTab === 'htaccess' ? (
                                            htaccessInfo.exists ? (
                                                <span className="text-green-600">Exists</span>
                                            ) : (
                                                <span className="text-amber-600">Will be created</span>
                                            )
                                        ) : (
                                            robotsInfo.exists ? (
                                                <span className="text-green-600">Exists</span>
                                            ) : (
                                                <span className="text-amber-600">Will be created</span>
                                            )
                                        )}
                                    </p>
                                    <p>
                                        <span className="font-medium">Writable:</span>{' '}
                                        {activeTab === 'htaccess' ? (
                                            htaccessInfo.writable ? (
                                                <span className="text-green-600">Yes</span>
                                            ) : (
                                                <span className="text-red-600">No (check permissions)</span>
                                            )
                                        ) : (
                                            robotsInfo.writable ? (
                                                <span className="text-green-600">Yes</span>
                                            ) : (
                                                <span className="text-red-600">No (check permissions)</span>
                                            )
                                        )}
                                    </p>
                                </div>
                                
                                {/* Editor */}
                                <div className="mb-4">
                                    <textarea
                                        value={activeTab === 'htaccess' ? htaccessContent : robotsContent}
                                        onChange={(e) => {
                                            if (activeTab === 'htaccess') {
                                                setHtaccessContent(e.target.value);
                                            } else {
                                                setRobotsContent(e.target.value);
                                            }
                                        }}
                                        className="w-full h-96 font-mono text-sm border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                                        spellCheck="false"
                                    />
                                </div>
                                
                                {/* Action Buttons */}
                                <div className="flex justify-between">
                                    <button
                                        onClick={handleDiscardChanges}
                                        disabled={!isContentModified() || saving}
                                        className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm 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-gray-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Discard Changes
                                    </button>
                                    
                                    <button
                                        onClick={activeTab === 'htaccess' ? handleSaveHtaccess : handleSaveRobots}
                                        disabled={!isContentModified() || saving || (activeTab === 'htaccess' ? !htaccessInfo.writable : !robotsInfo.writable)}
                                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        {saving ? 'Saving...' : 'Save Changes'}
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                    
                    {/* Suggestions Column */}
                    {showSuggestions && (
                        <div className="lg:col-span-1">
                            <div className="bg-amber-50 p-4 rounded-md">
                                <div className="flex justify-between items-center mb-4">
                                    <h3 className="text-lg font-medium text-amber-800">Smart Suggestions</h3>
                                    <button 
                                        onClick={() => setShowSuggestions(false)}
                                        className="text-amber-500 hover:text-amber-700"
                                    >
                                        <XMarkIcon className="h-5 w-5" />
                                    </button>
                                </div>
                                
                                <div className="space-y-4 max-h-[500px] overflow-y-auto pr-2">
                                    {(activeTab === 'htaccess' ? htaccessSuggestions : robotsSuggestions).length === 0 ? (
                                        <p className="text-amber-700 text-sm">No suggestions available.</p>
                                    ) : (
                                        (activeTab === 'htaccess' ? htaccessSuggestions : robotsSuggestions).map((suggestion, index) => (
                                            <div key={index} className="bg-white p-3 rounded-md shadow-sm">
                                                <h4 className="font-medium text-gray-900">{suggestion.title}</h4>
                                                <p className="text-sm text-gray-600 mt-1 mb-2">{suggestion.description}</p>
                                                <div className="bg-gray-50 p-2 rounded text-xs font-mono mb-2 max-h-32 overflow-y-auto">
                                                    <pre>{suggestion.code}</pre>
                                                </div>
                                                <div className="flex justify-between items-center">
                                                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                                        suggestion.type === 'security' ? 'bg-red-100 text-red-800' :
                                                        suggestion.type === 'performance' ? 'bg-blue-100 text-blue-800' :
                                                        'bg-green-100 text-green-800'
                                                    }`}>
                                                        {suggestion.type}
                                                    </span>
                                                    <button
                                                        onClick={() => handleApplySuggestion(suggestion)}
                                                        className="inline-flex items-center px-2 py-1 text-xs font-medium rounded text-amber-700 bg-amber-100 hover:bg-amber-200"
                                                    >
                                                        Apply
                                                    </button>
                                                </div>
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                    
                    {/* Backups Column */}
                    {showBackups && (
                        <div className="lg:col-span-1">
                            <div className="bg-indigo-50 p-4 rounded-md">
                                <div className="flex justify-between items-center mb-4">
                                    <h3 className="text-lg font-medium text-indigo-800">Backups</h3>
                                    <button 
                                        onClick={() => setShowBackups(false)}
                                        className="text-indigo-500 hover:text-indigo-700"
                                    >
                                        <XMarkIcon className="h-5 w-5" />
                                    </button>
                                </div>
                                
                                <div className="space-y-2 max-h-[500px] overflow-y-auto pr-2">
                                    {(activeTab === 'htaccess' ? htaccessBackups : robotsBackups).length === 0 ? (
                                        <p className="text-indigo-700 text-sm">No backups available.</p>
                                    ) : (
                                        (activeTab === 'htaccess' ? htaccessBackups : robotsBackups).map((backup, index) => (
                                            <div key={index} className="bg-white p-3 rounded-md shadow-sm flex justify-between items-center">
                                                <div>
                                                    <p className="font-medium text-sm text-gray-900">{backup.date}</p>
                                                    <p className="text-xs text-gray-500">{backup.file}</p>
                                                </div>
                                                <button
                                                    onClick={() => handleRestoreBackup(backup.file, activeTab === 'htaccess' ? 'htaccess' : 'robots')}
                                                    className="inline-flex items-center px-2 py-1 text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200"
                                                >
                                                    Restore
                                                </button>
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                </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>Properly configured .htaccess files can significantly improve site performance and security</li>
                        <li>Well-structured robots.txt helps search engines index your content correctly</li>
                        <li>Automatic backups ensure you can always revert to a working configuration</li>
                        <li>Smart suggestions help you implement best practices without technical expertise</li>
                    </ul>
                </div>
            </div>
        </Layout>
    );
};

export default FileTweaker;
