import React, { useState } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import ConfirmModal from '@/Components/ConfirmModal';
import { 
    Loader2, Server, Trash2, Zap, Database, Globe, FileCode, 
    RefreshCw, HardDrive, Link as LinkIcon 
} from 'lucide-react';

export default function SystemMaintenance() {
    const [loading, setLoading] = useState(null);
    
    const [modalConfig, setModalConfig] = useState({ 
        open: false, 
        type: null, 
        title: '', 
        desc: '' 
    });

    // Handler for simple actions (Cache Clear) - No Modal required
    const handleDirectAction = async (type, endpoint) => {
        setLoading(type);
        try {
            const res = await axios.post(endpoint, { type });
            toast.success("Success", { description: res.data.message });
        } catch (error) {
            toast.error("Error", { description: error.response?.data?.message || "Operation failed." });
        } finally {
            setLoading(null);
        }
    };

    // Modal Triggers for Sensitive Actions (DB & Storage)
    const initiateSensitiveAction = (type) => {
        if (type === 'migrate') {
            setModalConfig({
                open: true, type: 'migrate',
                title: 'Run Database Migrations?',
                desc: 'This will update your database structure. Ensure you have a backup before proceeding. This action cannot be undone.'
            });
        } else if (type === 'storage') {
            setModalConfig({
                open: true, type: 'storage',
                title: 'Recreate Storage Link?',
                desc: 'This will delete the existing public/storage symbolic link and create a new one. This typically resolves 404 errors for images.'
            });
        }
    };

    // Execute Action after Confirmation
    const executeSensitiveAction = async () => {
        const action = modalConfig.type;
        setModalConfig({ ...modalConfig, open: false });
        setLoading(action);

        try {
            let endpoint = '';
            if (action === 'migrate') endpoint = '/api/admin/system/migrate';
            else if (action === 'storage') endpoint = '/api/admin/system/storage-link';

            const res = await axios.post(endpoint);
            toast.success("Completed", { description: res.data.message });
        } catch (error) {
            toast.error("Failed", { description: error.response?.data?.message || "Operation failed." });
        } finally {
            setLoading(null);
        }
    };

    return (
        <AdminLayout header="Settings">
            <Head title="System Maintenance" />

            <ConfirmModal 
                open={modalConfig.open}
                onOpenChange={(open) => setModalConfig({ ...modalConfig, open })}
                onConfirm={executeSensitiveAction}
                title={modalConfig.title}
                description={modalConfig.desc}
                confirmText="Yes, Proceed"
                variant="destructive"
            />

            <SettingsLayout>
                <div className="space-y-6">
                    
                    {/* --- 1. CACHE MANAGEMENT (First) --- */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2"><Server className="w-5 h-5 text-primary" /> Cache Management</CardTitle>
                            <CardDescription>Clear application caches to resolve issues or apply configuration changes.</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-6 pt-4">
                            <div className="bg-primary/5 border border-primary/20 rounded-lg p-4 flex flex-col sm:flex-row items-center justify-between gap-4">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 bg-primary/10 rounded-full text-primary"><Zap className="w-6 h-6" /></div>
                                    <div>
                                        <h4 className="font-bold text-foreground">Optimize Clear (Recommended)</h4>
                                        <p className="text-sm text-muted-foreground">Clears all caches (Config, Route, Files) at once.</p>
                                    </div>
                                </div>
                                <Button onClick={() => handleDirectAction('optimize', '/api/admin/system/cache-clear')} disabled={loading !== null} className="min-w-[140px]">
                                    {loading === 'optimize' ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Trash2 className="mr-2 h-4 w-4" />} Clear All
                                </Button>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <CacheCard icon={Database} title="Application Cache" desc="Clears standard cache (Redis/File)." loading={loading === 'app'} onClick={() => handleDirectAction('app', '/api/admin/system/cache-clear')} disabled={loading !== null} />
                                <CacheCard icon={Globe} title="Route Cache" desc="Fixes 404s after adding new routes." loading={loading === 'route'} onClick={() => handleDirectAction('route', '/api/admin/system/cache-clear')} disabled={loading !== null} />
                                <CacheCard icon={Server} title="Configuration Cache" desc="Apply changes made to .env file." loading={loading === 'config'} onClick={() => handleDirectAction('config', '/api/admin/system/cache-clear')} disabled={loading !== null} />
                                <CacheCard icon={FileCode} title="View/Blade Cache" desc="Clear compiled view files." loading={loading === 'view'} onClick={() => handleDirectAction('view', '/api/admin/system/cache-clear')} disabled={loading !== null} />
                            </div>
                        </CardContent>
                    </Card>

                    {/* --- 2. APPLICATION UPDATES (Second) --- */}
                    <Card className="border-blue-200 dark:border-blue-900 bg-blue-50/50 dark:bg-blue-950/10">
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2 text-blue-700 dark:text-blue-400">
                                <RefreshCw className="w-5 h-5" /> Application Updates
                            </CardTitle>
                            <CardDescription>Run these commands only after updating the application code (git pull).</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex items-center justify-between p-4 bg-background rounded-lg border shadow-sm">
                                <div className="flex items-center gap-3">
                                    <Database className="w-5 h-5 text-blue-600" />
                                    <div>
                                        <h5 className="font-bold text-sm">Migrate Database</h5>
                                        <p className="text-xs text-muted-foreground">Update tables & columns.</p>
                                    </div>
                                </div>
                                <Button size="sm" onClick={() => initiateSensitiveAction('migrate')} disabled={loading !== null}>
                                    {loading === 'migrate' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Run Migration'}
                                </Button>
                            </div>
                        </CardContent>
                    </Card>

                    {/* --- 3. FILESYSTEM / STORAGE (Last) --- */}
                    <Card className="border-orange-200 dark:border-orange-900 bg-orange-50/50 dark:bg-orange-950/10">
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2 text-orange-700 dark:text-orange-400">
                                <HardDrive className="w-5 h-5" /> Filesystem & Storage
                            </CardTitle>
                            <CardDescription>Fix issues with missing images or broken file links.</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex items-center justify-between p-4 bg-background rounded-lg border shadow-sm">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 bg-muted rounded-full"><LinkIcon className="w-5 h-5 text-muted-foreground" /></div>
                                    <div>
                                        <h5 className="font-bold text-sm">Symlink Storage</h5>
                                        <p className="text-xs text-muted-foreground">Run if uploaded images are returning 404 errors.</p>
                                    </div>
                                </div>
                                <Button size="sm" onClick={() => initiateSensitiveAction('storage')} disabled={loading !== null}>
                                    {loading === 'storage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix Storage Link'}
                                </Button>
                            </div>
                        </CardContent>
                    </Card>

                </div>
            </SettingsLayout>
        </AdminLayout>
    );
}

function CacheCard({ icon: Icon, title, desc, loading, onClick, disabled }) {
    return (
        <div className="border rounded-lg p-4 flex items-center justify-between hover:bg-muted/30 transition-colors">
            <div className="flex items-center gap-3">
                <Icon className="w-5 h-5 text-muted-foreground" />
                <div><h5 className="font-medium text-sm">{title}</h5><p className="text-xs text-muted-foreground">{desc}</p></div>
            </div>
            <Button variant="outline" size="sm" onClick={onClick} disabled={disabled}>
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Clear'}
            </Button>
        </div>
    );
}