import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { Server, Database, Activity, AlertCircle } from "lucide-react";

export default async function AdminSystemPage() {
    const currentUser = await getCurrentUser();

    const isAdmin = currentUser && ["super_admin", "admin", "moderator", "analyst", "support"].includes(currentUser.role);

    if (!isAdmin) {
        redirect("/dashboard");
    }

    const database = await db.read();

    // Calculate system stats
    const stats = {
        totalUsers: database.users.length,
        totalJobs: database.jobs.length,
        totalApplications: database.applications.length,
        activeApplications: database.applications.filter(a => a.status !== 'rejected' && a.status !== 'accepted').length,
        recentActivity: database.applications.slice(-5).reverse()
    };

    return (
        <div className="space-y-6">
            {/* Header */}
            <div>
                <h1 className="text-3xl font-bold text-slate-900">System Management</h1>
                <p className="text-slate-600 mt-2">
                    Monitor system health and configure settings
                </p>
            </div>

            {/* System Status */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                <SystemMetric
                    label="System Status"
                    value="Operational"
                    icon={Server}
                    color="text-emerald-600"
                    bgColor="bg-emerald-50"
                />
                <SystemMetric
                    label="Database"
                    value="Healthy"
                    icon={Database}
                    color="text-blue-600"
                    bgColor="bg-blue-50"
                />
                <SystemMetric
                    label="API Response"
                    value="< 100ms"
                    icon={Activity}
                    color="text-purple-600"
                    bgColor="bg-purple-50"
                />
                <SystemMetric
                    label="Errors (24h)"
                    value="0"
                    icon={AlertCircle}
                    color="text-slate-600"
                    bgColor="bg-slate-50"
                />
            </div>

            <div className="grid gap-6 lg:grid-cols-2">
                {/* Database Statistics */}
                <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                    <h2 className="font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <Database className="h-5 w-5 text-blue-600" />
                        Database Statistics
                    </h2>
                    <div className="space-y-3">
                        <StatRow label="Total Users" value={stats.totalUsers} />
                        <StatRow label="Total Jobs" value={stats.totalJobs} />
                        <StatRow label="Total Applications" value={stats.totalApplications} />
                        <StatRow label="Active Applications" value={stats.activeApplications} />
                    </div>
                </div>

                {/* Recent Activity */}
                <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                    <h2 className="font-bold text-slate-900 mb-4 flex items-center gap-2">
                        <Activity className="h-5 w-5 text-purple-600" />
                        Recent Activity
                    </h2>
                    <div className="space-y-3">
                        {stats.recentActivity.map((activity) => {
                            const job = database.jobs.find(j => j.id === activity.jobId);
                            const candidate = database.users.find(u => u.id === activity.candidateId);
                            return (
                                <div key={activity.id} className="flex items-start gap-3 pb-3 border-b border-slate-100 last:border-0">
                                    <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                                        <Activity className="h-4 w-4 text-primary" />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className="text-sm text-slate-700">
                                            <span className="font-semibold">{candidate?.name || 'Applicant'}</span> applied to{' '}
                                            <span className="font-semibold">{job?.title || 'a position'}</span>
                                        </p>
                                        <p className="text-xs text-slate-500 mt-0.5">
                                            {new Date(activity.appliedAt).toLocaleString()}
                                        </p>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>

            {/* System Configuration */}
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                <h2 className="font-bold text-slate-900 mb-4">System Configuration</h2>
                <div className="space-y-4">
                    <ConfigOption
                        label="Email Notifications"
                        description="Send email notifications to users"
                        enabled={true}
                    />
                    <ConfigOption
                        label="Job Auto-Approval"
                        description="Automatically approve new job postings"
                        enabled={false}
                    />
                    <ConfigOption
                        label="Maintenance Mode"
                        description="Put the system in maintenance mode"
                        enabled={false}
                    />
                    <ConfigOption
                        label="Debug Mode"
                        description="Enable detailed error logging"
                        enabled={false}
                    />
                </div>
            </div>

            {/* Danger Zone */}
            <div className="rounded-2xl border border-red-100 bg-red-50 p-6">
                <h2 className="font-bold text-red-900 mb-2 flex items-center gap-2">
                    <AlertCircle className="h-5 w-5" />
                    Danger Zone
                </h2>
                <p className="text-sm text-red-700 mb-4">
                    These actions can have serious consequences. Use with caution.
                </p>
                <div className="flex gap-3">
                    <button className="px-4 py-2 bg-red-600 text-white rounded-lg font-semibold hover:bg-red-700 transition-colors text-sm">
                        Clear All Data
                    </button>
                    <button className="px-4 py-2 bg-red-600 text-white rounded-lg font-semibold hover:bg-red-700 transition-colors text-sm">
                        Reset Database
                    </button>
                </div>
            </div>
        </div>
    );
}

function SystemMetric({ label, value, icon: Icon, color, bgColor }: any) {
    return (
        <div className="rounded-xl bg-white p-6 border border-slate-100 shadow-sm">
            <div className="flex items-center gap-3">
                <div className={`h-12 w-12 rounded-lg ${bgColor} flex items-center justify-center`}>
                    <Icon className={`h-6 w-6 ${color}`} />
                </div>
                <div>
                    <p className="text-sm text-slate-500">{label}</p>
                    <p className={`text-lg font-bold ${color}`}>{value}</p>
                </div>
            </div>
        </div>
    );
}

function StatRow({ label, value }: { label: string; value: number }) {
    return (
        <div className="flex items-center justify-between py-2 border-b border-slate-100 last:border-0">
            <span className="text-sm text-slate-600">{label}</span>
            <span className="font-semibold text-slate-900">{value}</span>
        </div>
    );
}

function ConfigOption({ label, description, enabled }: { label: string; description: string; enabled: boolean }) {
    return (
        <div className="flex items-center justify-between py-3 border-b border-slate-100 last:border-0">
            <div>
                <p className="font-semibold text-slate-900">{label}</p>
                <p className="text-sm text-slate-500 mt-0.5">{description}</p>
            </div>
            <button
                className={`relative w-12 h-6 rounded-full transition-colors ${enabled ? 'bg-primary' : 'bg-slate-300'
                    }`}
            >
                <span
                    className={`absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white transition-transform ${enabled ? 'translate-x-6' : 'translate-x-0'
                        }`}
                />
            </button>
        </div>
    );
}
