import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { AdminService } from "@/services/AdminService";
import { StatCard } from "@/components/admin/StatCard";
import { ActivityTimeline } from "@/components/admin/ActivityTimeline";
import { QuickActions } from "@/components/admin/QuickActions";
import { MiniChart } from "@/components/admin/MiniChart";
import { SystemHealth } from "@/components/admin/SystemHealth";
import { ModerationAnalytics } from "@/components/admin/ModerationAnalytics";
import Link from "next/link";
import {
    Clock, Briefcase, Users, FileText,
    ArrowRight
} from "lucide-react";

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

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

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

    // Fetch all dashboard data in parallel
    const [stats, recentActivity, recentJobs, jobTrends, userGrowth, systemHealth, moderationAnalytics] =
        await Promise.all([
            AdminService.getDashboardStats(),
            AdminService.getRecentActivity(15),
            AdminService.getRecentJobs(10),
            AdminService.getJobTrends(7),
            AdminService.getUserGrowth(7),
            AdminService.getSystemHealth(),
            AdminService.getModerationAnalytics(),
        ]);

    // Transform trend data for chart
    const jobChartData = jobTrends.map((point) => ({
        label: point.label,
        values: [
            { name: "Posted", value: point.posted, color: "#3b82f6" },
            { name: "Published", value: point.published, color: "#10b981" },
        ],
    }));

    const userChartData = userGrowth.map((point) => ({
        label: point.label,
        values: [
            { name: "Candidates", value: point.candidates, color: "#3b82f6" },
            { name: "Employers", value: point.employers, color: "#8b5cf6" },
        ],
    }));

    return (
        <div className="space-y-6">
            {/* Page Header */}
            <div>
                <h1 className="text-2xl font-bold text-slate-900">Dashboard Overview</h1>
                <p className="mt-1 text-sm text-slate-500">
                    Welcome back, {currentUser.name}. Here&apos;s what&apos;s happening on your platform.
                </p>
            </div>

            {/* Row 1 — Stat Cards */}
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <StatCard
                    label="Pending Approvals"
                    value={stats.pendingApprovals}
                    icon={Clock}
                    color="orange"
                    subtext={`${stats.pendingUrgent} pending > 24h`}
                    href="/admin/approvals"
                />
                <StatCard
                    label="Active Jobs"
                    value={stats.activeJobs}
                    icon={Briefcase}
                    color="blue"
                    subtext={`${stats.expiringThisWeek} expiring this week`}
                    href="/admin/jobs"
                />
                <StatCard
                    label="Total Users"
                    value={stats.totalUsers}
                    icon={Users}
                    color="green"
                    subtext={`${stats.newUsersThisWeek} new this week`}
                    href="/admin/users"
                />
                <StatCard
                    label="Applications Today"
                    value={stats.applicationsToday}
                    icon={FileText}
                    color="purple"
                    trend={stats.applicationsTrend}
                    trendLabel="vs yesterday"
                />
            </div>

            {/* Moderation Performance Section */}
            <div className="space-y-4">
                <h2 className="text-sm font-semibold text-slate-700 px-1">Moderation Performance</h2>
                <ModerationAnalytics data={moderationAnalytics} />
            </div>

            {/* Row 2 — Activity Timeline + Quick Actions */}
            <div className="grid gap-6 lg:grid-cols-5">
                {/* Activity Timeline — 60% */}
                <div className="lg:col-span-3">
                    <div className="rounded-2xl border border-slate-100 bg-white shadow-sm">
                        <div className="flex items-center justify-between border-b border-slate-50 px-6 py-4">
                            <h2 className="text-sm font-semibold text-slate-700">Recent Activity</h2>
                            <span className="text-xs text-slate-400">Last 24 hours</span>
                        </div>
                        <div className="max-h-[400px] overflow-y-auto p-3">
                            <ActivityTimeline events={recentActivity} />
                        </div>
                    </div>
                </div>

                {/* Quick Actions — 40% */}
                <div className="lg:col-span-2">
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <h2 className="mb-4 text-sm font-semibold text-slate-700">Quick Actions</h2>
                        <QuickActions
                            pendingApprovals={stats.pendingApprovals}
                            reportedContent={0}
                        />
                    </div>
                </div>
            </div>

            {/* Row 3 — Charts */}
            <div className="grid gap-6 lg:grid-cols-2">
                <MiniChart title="Job Postings (Last 7 Days)" data={jobChartData} />
                <MiniChart title="User Growth (Last 7 Days)" data={userChartData} />
            </div>

            {/* Row 4 — Recent Jobs Table */}
            <div className="rounded-2xl border border-slate-100 bg-white shadow-sm">
                <div className="flex items-center justify-between border-b border-slate-50 px-6 py-4">
                    <h2 className="text-sm font-semibold text-slate-700">Recently Submitted Jobs</h2>
                    <Link
                        href="/admin/jobs"
                        className="flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700"
                    >
                        View All <ArrowRight className="h-3 w-3" />
                    </Link>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead className="border-b border-slate-50 bg-slate-50/50">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Job Title
                                </th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Company
                                </th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Posted By
                                </th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Submitted
                                </th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Status
                                </th>
                                <th className="px-6 py-3 text-right text-xs font-semibold uppercase tracking-wider text-slate-500">
                                    Action
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-50">
                            {recentJobs.map((job) => {
                                const timeAgo = getTimeAgo(job.submittedAt);
                                return (
                                    <tr key={job.id} className="hover:bg-slate-50/50 transition-colors">
                                        <td className="px-6 py-3.5">
                                            <Link
                                                href={`/jobs/${job.id}`}
                                                className="text-sm font-semibold text-slate-900 hover:text-blue-600"
                                            >
                                                {job.title}
                                            </Link>
                                            {job.isFeatured && (
                                                <span className="ml-2 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-bold text-amber-600">
                                                    FEATURED
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-6 py-3.5 text-sm text-slate-600">{job.company}</td>
                                        <td className="px-6 py-3.5">
                                            <p className="text-sm text-slate-700">{job.postedBy}</p>
                                        </td>
                                        <td className="px-6 py-3.5 text-sm text-slate-500">{timeAgo}</td>
                                        <td className="px-6 py-3.5">
                                            <StatusBadge status={job.status} />
                                        </td>
                                        <td className="px-6 py-3.5 text-right">
                                            <Link
                                                href={`/jobs/${job.id}`}
                                                className="rounded-md px-3 py-1.5 text-xs font-medium text-blue-600 hover:bg-blue-50 transition-colors"
                                            >
                                                {job.status === "draft" ? "Review" : "View"}
                                            </Link>
                                        </td>
                                    </tr>
                                );
                            })}
                            {recentJobs.length === 0 && (
                                <tr>
                                    <td colSpan={6} className="py-12 text-center text-sm text-slate-400">
                                        No jobs submitted yet
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Row 5 — System Health */}
            <SystemHealth items={systemHealth} />
        </div>
    );
}

// Helper components
function StatusBadge({ status }: { status: string }) {
    const styles: Record<string, string> = {
        draft: "bg-orange-50 text-orange-600 border-orange-100",
        published: "bg-emerald-50 text-emerald-600 border-emerald-100",
        paused: "bg-slate-50 text-slate-600 border-slate-100",
        closed: "bg-red-50 text-red-600 border-red-100",
        expired: "bg-slate-50 text-slate-500 border-slate-100",
    };

    return (
        <span className={`inline-flex rounded-full border px-2.5 py-0.5 text-[11px] font-semibold capitalize ${styles[status] || styles.draft}`}>
            {status === "draft" ? "Pending" : status}
        </span>
    );
}

function getTimeAgo(dateStr: string): string {
    const seconds = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
    if (seconds < 60) return "Just now";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days === 1) return "Yesterday";
    if (days < 7) return `${days} days ago`;
    return new Date(dateStr).toLocaleDateString("en-US", { month: "short", day: "numeric" });
}
