import React, { useState } from 'react';
import { Head, router, usePage } from '@inertiajs/react';
import { toast } from 'sonner'; 
import AdminLayout from '@/cp/Layouts/AdminLayout';
import ConfirmModal from '@/Components/ConfirmModal'; 
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/Components/ui/tooltip";
import { 
    ServerCrash, Database, FileCode2, Settings2, AppWindow, 
    Loader2, Link as LinkIcon, DatabaseBackup, Info 
} from "lucide-react";

export default function Maintenance() {
    const { errors } = usePage().props;
    const [loadingAction, setLoadingAction] = useState(null);
    
    // Modal State
    const [isConfirmOpen, setIsConfirmOpen] = useState(false);
    const [selectedAction, setSelectedAction] = useState(null);

    // 1. Open the confirmation modal
    const confirmAction = (actionId, actionName, routeName, payload = {}) => {
        setSelectedAction({ id: actionId, name: actionName, routeName, payload });
        setIsConfirmOpen(true);
    };

    // 2. Execute the action after confirmation
    const executeAction = () => {
        if (!selectedAction) return;

        setLoadingAction(selectedAction.id);
        setIsConfirmOpen(false); // Close modal immediately

        router.post(route(selectedAction.routeName), selectedAction.payload, {
            preserveScroll: true,
            onSuccess: (page) => {
                if (page.props.errors?.error) {
                    toast.error(page.props.errors.error);
                } else {
                    toast.success(page.props.flash?.success || `Successfully executed: ${selectedAction.name}`);
                }
            },
            onError: (err) => {
                toast.error(err.error || `Failed to execute ${selectedAction.name}. Please try again.`);
            },
            onFinish: () => {
                setLoadingAction(null);
                setSelectedAction(null);
            }
        });
    };

    const cacheOptions = [
        { id: 'cache', name: 'Application Cache', desc: 'Clears the general application cache (Redis/File/DB).', icon: Database },
        { id: 'route', name: 'Route Cache', desc: 'Clears the route cache. Use when you add/modify routes.', icon: FileCode2 },
        { id: 'config', name: 'Config Cache', desc: 'Clears cached configurations. Use when you change .env values.', icon: Settings2 },
        { id: 'view', name: 'View Cache', desc: 'Clears compiled Blade view files.', icon: AppWindow },
    ];

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

            {/* Global Confirmation Modal */}
            <ConfirmModal 
                open={isConfirmOpen}
                onOpenChange={setIsConfirmOpen}
                onConfirm={executeAction}
                title={`${selectedAction?.name}?`}
                description="Are you sure you want to perform this action? This may temporarily affect application performance while the system rebuilds."
                confirmText="Yes, Execute Action"
                variant={selectedAction?.id === 'all' ? 'destructive' : 'default'}
            />

            <div className="max-w-4xl mx-auto pb-12">
                <div className="flex items-center gap-3 mb-6">
                    <ServerCrash className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">System Maintenance</h2>
                        <p className="text-muted-foreground">Manage application performance, cache, and structural configurations.</p>
                    </div>
                </div>

                {errors?.error && (
                    <div className="mb-6 p-4 bg-red-500/10 border border-red-500/20 text-red-600 rounded-lg font-bold text-sm">
                        {errors.error}
                    </div>
                )}

                <div className="grid gap-6">
                    {/* Optimize Clear (The Big Button) */}
                    <Card className="border-destructive/20 shadow-sm bg-destructive/5">
                        <CardHeader>
                            <CardTitle className="text-destructive">Optimize Clear (Clear All)</CardTitle>
                            <CardDescription>
                                This will safely clear <b>all</b> cached data including routes, views, config, and application cache. 
                                It is equivalent to running <code>php artisan optimize:clear</code>.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <Button 
                                variant="destructive" 
                                size="lg"
                                className="w-full sm:w-auto"
                                disabled={loadingAction !== null}
                                onClick={() => confirmAction('all', 'Clear All Caches', 'cp.system.cache.clear', { action: 'all' })}
                            >
                                {loadingAction === 'all' && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                Clear All System Caches
                            </Button>
                        </CardContent>
                    </Card>

                    {/* Individual Caches */}
                    <Card>
                        <CardHeader>
                            <CardTitle>Specific Cache Management</CardTitle>
                            <CardDescription>Clear specific parts of the framework if you only updated certain files.</CardDescription>
                        </CardHeader>
                        <CardContent className="grid sm:grid-cols-2 gap-4">
                            {cacheOptions.map((opt) => (
                                <div key={opt.id} className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 border rounded-xl bg-card hover:bg-muted/50 transition-colors">
                                    <div className="flex items-center gap-3">
                                        <div className="p-2 rounded-lg bg-primary/10 text-primary shrink-0">
                                            <opt.icon className="w-5 h-5" />
                                        </div>
                                        <div>
                                            <h4 className="font-semibold text-sm">{opt.name}</h4>
                                            <p className="text-xs text-muted-foreground mt-0.5">{opt.desc}</p>
                                        </div>
                                    </div>
                                    <Button 
                                        variant="outline" 
                                        size="sm" 
                                        className="w-full sm:w-auto shrink-0"
                                        disabled={loadingAction !== null}
                                        onClick={() => confirmAction(opt.id, `Clear ${opt.name}`, 'cp.system.cache.clear', { action: opt.id })}
                                    >
                                        {loadingAction === opt.id ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Clear'}
                                    </Button>
                                </div>
                            ))}
                        </CardContent>
                    </Card>

                    {/* NEW: ADVANCED SYSTEM OPERATIONS */}
                    <Card className="border-orange-500/20 shadow-sm bg-orange-500/5">
                        <CardHeader>
                            <CardTitle className="text-orange-700 dark:text-orange-500">Advanced System Operations</CardTitle>
                            <CardDescription className="text-orange-600/80">Use these tools for core application setup and version upgrades.</CardDescription>
                        </CardHeader>
                        <CardContent className="grid sm:grid-cols-2 gap-4">
                            
                            {/* Storage Symlink */}
                            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 border border-orange-500/20 rounded-xl bg-background shadow-sm">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 rounded-lg bg-orange-500/10 text-orange-600 shrink-0">
                                        <LinkIcon className="w-5 h-5" />
                                    </div>
                                    <div>
                                        <h4 className="font-semibold text-sm flex items-center gap-1.5">
                                            Storage Symlink
                                            <TooltipProvider>
                                                <Tooltip delayDuration={100}>
                                                    <TooltipTrigger type="button" className="cursor-help mt-0.5">
                                                        <Info className="w-3.5 h-3.5 text-muted-foreground hover:text-foreground transition-colors" />
                                                    </TooltipTrigger>
                                                    <TooltipContent className="max-w-xs shadow-xl border-orange-500/20">
                                                        <p className="text-xs">Click this button if your product images or media are broken/not showing. It securely deletes any broken links and recreates the public storage directory.</p>
                                                    </TooltipContent>
                                                </Tooltip>
                                            </TooltipProvider>
                                        </h4>
                                        <p className="text-xs text-muted-foreground mt-0.5">Fixes broken media files.</p>
                                    </div>
                                </div>
                                <Button 
                                    variant="secondary" 
                                    size="sm" 
                                    className="w-full sm:w-auto shrink-0 bg-white dark:bg-black border border-orange-500/30 hover:bg-orange-500/10 text-orange-600"
                                    disabled={loadingAction !== null}
                                    onClick={() => confirmAction('symlink', 'Recreate Storage Symlink', 'cp.system.storage.link')}
                                >
                                    {loadingAction === 'symlink' ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Run Link'}
                                </Button>
                            </div>

                            {/* Database Migrations */}
                            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 border border-orange-500/20 rounded-xl bg-background shadow-sm">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 rounded-lg bg-orange-500/10 text-orange-600 shrink-0">
                                        <DatabaseBackup className="w-5 h-5" />
                                    </div>
                                    <div>
                                        <h4 className="font-semibold text-sm flex items-center gap-1.5">
                                            Database Migrations
                                            <TooltipProvider>
                                                <Tooltip delayDuration={100}>
                                                    <TooltipTrigger type="button" className="cursor-help mt-0.5">
                                                        <Info className="w-3.5 h-3.5 text-muted-foreground hover:text-foreground transition-colors" />
                                                    </TooltipTrigger>
                                                    <TooltipContent className="max-w-xs shadow-xl border-orange-500/20">
                                                        <p className="text-xs">When the application is updated to a new version, run this to safely apply any new database tables and columns required by the new code.</p>
                                                    </TooltipContent>
                                                </Tooltip>
                                            </TooltipProvider>
                                        </h4>
                                        <p className="text-xs text-muted-foreground mt-0.5">Applies new software updates.</p>
                                    </div>
                                </div>
                                <Button 
                                    variant="secondary" 
                                    size="sm" 
                                    className="w-full sm:w-auto shrink-0 bg-white dark:bg-black border border-orange-500/30 hover:bg-orange-500/10 text-orange-600"
                                    disabled={loadingAction !== null}
                                    onClick={() => confirmAction('migrate', 'Run Database Migrations', 'cp.system.migrate')}
                                >
                                    {loadingAction === 'migrate' ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Run Migrate'}
                                </Button>
                            </div>

                        </CardContent>
                    </Card>

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