import AdminLayout from '@/Layouts/AdminLayout';
import { Head, router, Link } from '@inertiajs/react';
import { 
    Terminal, 
    Database, 
    Zap, 
    RefreshCw, 
    ShieldCheck, 
    AlertCircle, 
    ChevronRight, 
    HardDrive, 
    Cpu, 
    Info,
    ArrowLeft
} from 'lucide-react';
import { toast } from 'sonner';
import { motion } from 'framer-motion';

interface Props {
    system: {
        db_status: string;
        php_version: string;
        laravel_version: string;
        environment: string;
        pending_migrations: number;
        total_migrations: number;
    };
}

export default function DeploymentManager({ system }: Props) {
    const runAction = (action: string, label: string) => {
        if (confirm(`Are you sure you want to run: ${label}?`)) {
            router.post(route('admin.system.deploy'), { action }, {
                onSuccess: () => toast.success(`${label} completed successfully`),
                onError: (err) => toast.error(`Error: ${Object.values(err)[0]}`),
            });
        }
    };

    const stats = [
        { label: 'Database', value: system.db_status, icon: Database, color: 'text-emerald-600', bg: 'bg-emerald-50' },
        { label: 'PHP Version', value: system.php_version, icon: Cpu, color: 'text-blue-600', bg: 'bg-blue-50' },
        { label: 'Laravel', value: system.laravel_version, icon: Zap, color: 'text-red-600', bg: 'bg-red-50' },
        { label: 'Environment', value: system.environment, icon: HardDrive, color: 'text-amber-600', bg: 'bg-amber-50' },
    ];

    const actions = [
        { 
            id: 'migrate', 
            name: 'Run Migrations', 
            description: 'Update database schema with pending changes.',
            icon: RefreshCw,
            warning: system.pending_migrations > 0 ? `${system.pending_migrations} migrations pending` : null
        },
        { 
            id: 'seed', 
            name: 'Seed Database', 
            description: 'Fill database with default or sample data.',
            icon: Database 
        },
        { 
            id: 'clear_cache', 
            name: 'Clear All Cache', 
            description: 'Purge application, route, and config cache.',
            icon: Zap 
        },
        { 
            id: 'storage_link', 
            name: 'Link Storage', 
            description: 'Connect public storage to app directory.',
            icon: HardDrive 
        },
    ];

    return (
        <AdminLayout>
            <Head title="Deployment Manager" />

            <div className="mb-8">
                <Link 
                    href={route('admin.settings.index')}
                    className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] hover:text-ink transition-colors mb-4"
                >
                    <ArrowLeft className="h-3 w-3" />
                    Back to Settings
                </Link>
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    Deployment Manager
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    Manage system infrastructure and database state for shared hosting.
                </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                {stats.map((stat, i) => (
                    <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: i * 0.1 }}
                        key={stat.label}
                        className="bg-white p-5 rounded-2xl border border-[#E8E6DF] flex items-center gap-4"
                    >
                        <div className={`h-12 w-12 rounded-xl ${stat.bg} flex items-center justify-center ${stat.color}`}>
                            <stat.icon size={24} strokeWidth={1.5} />
                        </div>
                        <div>
                            <p className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-widest">{stat.label}</p>
                            <p className="text-[15px] font-bold text-ink mt-0.5">{stat.value}</p>
                        </div>
                    </motion.div>
                ))}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div className="lg:col-span-2 space-y-4">
                    <h2 className="text-[14px] font-bold text-ink uppercase tracking-wider px-1">Infrastructure Actions</h2>
                    <div className="grid gap-4">
                        {actions.map((action) => (
                            <button
                                key={action.id}
                                onClick={() => runAction(action.id, action.name)}
                                className="group flex items-center justify-between p-6 bg-white border border-[#E8E6DF] rounded-2xl transition-all hover:border-accent hover:shadow-lg hover:shadow-accent/5 text-left"
                            >
                                <div className="flex items-center gap-5">
                                    <div className="h-14 w-14 rounded-2xl bg-[#FAFAF8] border border-[#F0EDE8] flex items-center justify-center text-ink group-hover:bg-accent group-hover:text-white group-hover:border-accent transition-all">
                                        <action.icon size={24} strokeWidth={1.5} />
                                    </div>
                                    <div>
                                        <h3 className="text-[16px] font-bold text-ink">{action.name}</h3>
                                        <p className="text-[13px] text-[#8C92AC] mt-1">{action.description}</p>
                                        {action.warning && (
                                            <div className="mt-2 inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-50 text-amber-600 rounded-lg text-[11px] font-bold uppercase tracking-wider">
                                                <AlertCircle size={12} />
                                                {action.warning}
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className="h-10 w-10 rounded-full bg-[#F5F3EF] flex items-center justify-center text-[#C0BDBA] group-hover:bg-accent/10 group-hover:text-accent transition-all">
                                    <ChevronRight size={20} />
                                </div>
                            </button>
                        ))}
                    </div>
                </div>

                <div className="space-y-6">
                    <div className="bg-ink text-white rounded-3xl p-8 overflow-hidden relative group">
                        <div className="absolute top-0 right-0 p-8 opacity-10 group-hover:scale-110 transition-transform">
                            <Terminal size={120} />
                        </div>
                        <div className="relative z-10">
                            <div className="h-10 w-10 rounded-xl bg-white/10 flex items-center justify-center mb-6">
                                <ShieldCheck className="text-accent" />
                            </div>
                            <h3 className="text-[20px] font-bold mb-3">System Health</h3>
                            <p className="text-[14px] text-white/60 mb-6 leading-relaxed">
                                Your platform is currently running in <strong>{system.environment}</strong> mode. All systems are performing within normal parameters.
                            </p>
                            <div className="space-y-3">
                                <div className="flex items-center justify-between py-2 border-b border-white/10 text-[13px]">
                                    <span className="text-white/40">Migrations</span>
                                    <span className="font-mono">{system.total_migrations - system.pending_migrations}/{system.total_migrations}</span>
                                </div>
                                <div className="flex items-center justify-between py-2 border-b border-white/10 text-[13px]">
                                    <span className="text-white/40">Storage</span>
                                    <span className="text-emerald-400">Writable</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="bg-[#F0EDE8]/50 rounded-3xl p-8 border border-[#E8E6DF]">
                        <div className="flex items-center gap-3 mb-4">
                            <Info className="text-accent" size={20} />
                            <h3 className="text-[14px] font-bold text-ink uppercase tracking-wider">Deployment Tip</h3>
                        </div>
                        <p className="text-[13px] text-[#8C92AC] leading-relaxed">
                            After uploading new code files to your shared hosting server, always run <strong>Migrations</strong> followed by <strong>Clear Cache</strong> to ensure your updates are live and the database is in sync.
                        </p>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
