import React, { useState } from 'react';
import { router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import {
    Database,
    Zap,
    Download,
    RefreshCw,
    Clock,
    Layers,
    FileArchive,
    HardDrive,
    CheckCircle2,
    ShieldCheck,
    AlertTriangle,
} from 'lucide-react';

interface DatabaseProps {
    dbStatus: {
        driver: string;
        size_bytes: number;
        size_formatted: string;
        tables_count: number;
        total_rows: number;
        latest_backup: {
            exists: boolean;
            filename: string;
            size_bytes: number;
            size_formatted: string;
            last_modified: string;
            last_modified_relative: string;
        } | null;
    };
}

export default function Index({ dbStatus }: DatabaseProps) {
    const [optimizing, setOptimizing] = useState(false);
    const [backingUp, setBackingUp] = useState(false);

    const handleOptimize = () => {
        setOptimizing(true);
        router.post('/admin/database/optimize', {}, {
            preserveScroll: true,
            onFinish: () => setOptimizing(false),
        });
    };

    const handleBackup = () => {
        setBackingUp(true);
        router.post('/admin/database/backup', {}, {
            preserveScroll: true,
            onFinish: () => setBackingUp(false),
        });
    };

    return (
        <AdminLayout title="Database Maintenance & Compressed Backups">
            <SEOHead
                title="Database & Backups | Tech in Soul Admin"
                description="Optimize database performance, rebuild indexes, and manage compressed .sql.zip automated backups."
            />

            <div className="space-y-8">
                {/* Header overview */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-xl font-bold text-white flex items-center gap-2">
                            <Database className="w-6 h-6 text-[#00F2FE]" /> Database Engine & Backup Center
                        </h2>
                        <p className="text-xs text-slate-400">
                            Perform database indexing, disk optimization (VACUUM), and download compressed (.sql.zip) backups.
                        </p>
                    </div>

                    <div className="flex items-center gap-3">
                        <button
                            onClick={handleOptimize}
                            disabled={optimizing}
                            className="px-4 py-2 rounded-xl text-xs font-bold bg-amber-500/10 text-amber-300 border border-amber-500/30 hover:bg-amber-500/20 flex items-center gap-1.5 transition-all"
                        >
                            <Zap className={`w-4 h-4 ${optimizing ? 'animate-spin' : ''}`} />
                            {optimizing ? 'Optimizing...' : 'Optimize Database'}
                        </button>

                        <button
                            onClick={handleBackup}
                            disabled={backingUp}
                            className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5"
                        >
                            <RefreshCw className={`w-4 h-4 ${backingUp ? 'animate-spin' : ''}`} />
                            {backingUp ? 'Compressing...' : (dbStatus.latest_backup ? 'Regenerate .sql.zip' : 'Create .sql.zip Backup')}
                        </button>
                    </div>
                </div>

                {/* Metrics Grid */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
                    <div className="glass-card rounded-2xl p-5 border border-slate-800 space-y-2">
                        <div className="flex items-center justify-between text-slate-400 text-xs font-semibold uppercase">
                            <span>Engine Driver</span>
                            <HardDrive className="w-4 h-4 text-[#00F2FE]" />
                        </div>
                        <div className="text-2xl font-extrabold text-white uppercase tracking-wider font-mono">
                            {dbStatus.driver}
                        </div>
                        <p className="text-[11px] text-slate-500">Live Production Storage</p>
                    </div>

                    <div className="glass-card rounded-2xl p-5 border border-slate-800 space-y-2">
                        <div className="flex items-center justify-between text-slate-400 text-xs font-semibold uppercase">
                            <span>Database Live Size</span>
                            <HardDrive className="w-4 h-4 text-emerald-400" />
                        </div>
                        <div className="text-2xl font-extrabold text-white font-mono">
                            {dbStatus.size_formatted}
                        </div>
                        <p className="text-[11px] text-emerald-400 font-mono">Vacuum & Compression Ready</p>
                    </div>

                    <div className="glass-card rounded-2xl p-5 border border-slate-800 space-y-2">
                        <div className="flex items-center justify-between text-slate-400 text-xs font-semibold uppercase">
                            <span>Total Tables</span>
                            <Layers className="w-4 h-4 text-cyan-400" />
                        </div>
                        <div className="text-2xl font-extrabold text-white font-mono">
                            {dbStatus.tables_count} Tables
                        </div>
                        <p className="text-[11px] text-slate-500">{dbStatus.total_rows.toLocaleString()} Total Records</p>
                    </div>

                    <div className="glass-card rounded-2xl p-5 border border-slate-800 space-y-2">
                        <div className="flex items-center justify-between text-slate-400 text-xs font-semibold uppercase">
                            <span>Hourly Auto-Backup</span>
                            <Clock className="w-4 h-4 text-violet-400" />
                        </div>
                        <div className="text-2xl font-extrabold text-emerald-400 font-mono flex items-center gap-1.5">
                            <CheckCircle2 className="w-5 h-5 text-emerald-400" /> Active
                        </div>
                        <p className="text-[11px] text-slate-500">Every 1 hour (Scheduled)</p>
                    </div>
                </div>

                {/* Backup Status & Download Card */}
                <div className="glass-card rounded-2xl p-6 sm:p-8 border border-[#00F2FE]/20 space-y-6">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-6 border-b border-slate-800">
                        <div className="space-y-1">
                            <h3 className="text-base font-bold text-white flex items-center gap-2">
                                <FileArchive className="w-5 h-5 text-[#00F2FE]" />
                                Compressed SQL Archive (.sql.zip)
                            </h3>
                            <p className="text-xs text-slate-400">
                                Dumps full database schema DDL & record DML statements, compressed in standard ZIP container for maximum security and minimal file size.
                            </p>
                        </div>

                        {dbStatus.latest_backup ? (
                            <a
                                href="/admin/database/download"
                                className="btn-aqua px-6 py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2 shadow-[0_0_25px_rgba(0,242,254,0.3)] shrink-0"
                            >
                                <Download className="w-4 h-4" /> Download Latest .sql.zip ({dbStatus.latest_backup.size_formatted})
                            </a>
                        ) : (
                            <button
                                onClick={handleBackup}
                                disabled={backingUp}
                                className="btn-aqua px-6 py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2 shrink-0"
                            >
                                <RefreshCw className={`w-4 h-4 ${backingUp ? 'animate-spin' : ''}`} />
                                Generate Initial Backup (.sql.zip)
                            </button>
                        )}
                    </div>

                    {dbStatus.latest_backup ? (
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 bg-[#060B18] p-4 rounded-xl border border-slate-800/80">
                            <div>
                                <span className="text-[11px] font-semibold text-slate-400 uppercase block">Backup File</span>
                                <span className="text-xs font-mono text-[#00F2FE] break-all">{dbStatus.latest_backup.filename}</span>
                            </div>
                            <div>
                                <span className="text-[11px] font-semibold text-slate-400 uppercase block">Compressed Size</span>
                                <span className="text-xs font-mono text-emerald-400">{dbStatus.latest_backup.size_formatted}</span>
                            </div>
                            <div>
                                <span className="text-[11px] font-semibold text-slate-400 uppercase block">Last Backup Generated</span>
                                <span className="text-xs text-slate-300">
                                    {dbStatus.latest_backup.last_modified} ({dbStatus.latest_backup.last_modified_relative})
                                </span>
                            </div>
                        </div>
                    ) : (
                        <div className="p-4 rounded-xl bg-amber-500/10 border border-amber-500/20 text-xs text-amber-300 flex items-center gap-2">
                            <AlertTriangle className="w-4 h-4 shrink-0" />
                            No backup file generated yet. Click "Generate Initial Backup" above or wait for the automatic hourly cron job.
                        </div>
                    )}

                    {/* Security & Reliability Notes */}
                    <div className="pt-2 flex flex-col sm:flex-row items-start gap-3 text-xs text-slate-400">
                        <ShieldCheck className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />
                        <div>
                            <strong className="text-white">Enterprise Disaster Recovery & Security Assurance:</strong>
                            <p className="mt-0.5 leading-relaxed text-slate-400">
                                Backup archives are created locally in private application storage (<code className="text-[#00F2FE] font-mono">storage/app/backups/</code>) with restricted permissions (0755) and are never exposed publicly. Automated hourly backups are executed via Laravel Scheduler (<code className="text-[#00F2FE] font-mono">php artisan db:backup-zip</code>).
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
