import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import { Briefcase, Search, Clock, CheckCircle2, XCircle, MoreVertical } from "lucide-react";
import { JobActions } from "@/components/admin/JobActions";

export default async function AdminJobsPage(props: { searchParams: Promise<{ q?: string; type?: string }> }) {
    const searchParams = await props.searchParams;
    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();
    const query = searchParams.q?.toLowerCase() || "";

    // Filter jobs
    const filteredJobs = database.jobs.filter(job =>
        job.title.toLowerCase().includes(query) ||
        job.company.toLowerCase().includes(query)
    );

    const stats = {
        total: database.jobs.length,
        featured: database.jobs.filter(j => j.featured).length,
        applications: database.applications.length
    };

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900">Job Management</h1>
                    <p className="text-slate-600 mt-2">
                        Moderate and manage all job postings
                    </p>
                </div>
                <Link
                    href="/dashboard/employer/post-job"
                    className="px-4 py-2 bg-primary text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
                >
                    Post New Job
                </Link>
            </div>

            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-3">
                <StatCard label="Total Jobs" value={stats.total} icon={Briefcase} color="bg-blue-500" />
                <StatCard label="Featured Jobs" value={stats.featured} icon={CheckCircle2} color="bg-amber-500" />
                <StatCard label="Total Applications" value={stats.applications} icon={Clock} color="bg-emerald-500" />
            </div>

            {/* Search */}
            <div className="relative">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-400" />
                <input
                    type="text"
                    placeholder="Search jobs by title or company..."
                    defaultValue={query}
                    className="w-full pl-12 pr-4 py-3 rounded-xl border border-slate-200 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                />
            </div>

            {/* Jobs Table */}
            <div className="rounded-2xl border border-slate-100 bg-white shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead className="bg-slate-50 border-b border-slate-100">
                            <tr>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Job
                                </th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Company
                                </th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Type
                                </th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Applications
                                </th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Posted
                                </th>
                                <th className="px-6 py-4 text-right text-xs font-bold text-slate-600 uppercase tracking-wider">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {filteredJobs.map((job) => (
                                <tr key={job.id} className="hover:bg-slate-50 transition-colors">
                                    <td className="px-6 py-4">
                                        <div>
                                            <Link
                                                href={`/jobs/${job.id}`}
                                                className="font-semibold text-slate-900 hover:text-primary"
                                            >
                                                {job.title}
                                            </Link>
                                            {job.featured && (
                                                <span className="ml-2 px-2 py-0.5 rounded text-xs font-bold bg-amber-50 text-amber-600">
                                                    Featured
                                                </span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4">
                                        <p className="text-sm text-slate-700">{job.company}</p>
                                    </td>
                                    <td className="px-6 py-4">
                                        <span className="px-3 py-1 rounded-full text-xs font-medium bg-slate-100 text-slate-700">
                                            {job.type}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4">
                                        <p className="text-sm font-semibold text-slate-900">
                                            {job.applicants || 0}
                                        </p>
                                    </td>
                                    <td className="px-6 py-4">
                                        <p className="text-sm text-slate-600">
                                            {new Date(job.postedAt).toLocaleDateString()}
                                        </p>
                                    </td>
                                    <td className="px-6 py-4 text-right">
                                        <JobActions jobId={job.id} isFeatured={!!job.featured} />
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                {filteredJobs.length === 0 && (
                    <div className="text-center py-12">
                        <Briefcase className="h-12 w-12 text-slate-300 mx-auto mb-3" />
                        <p className="text-slate-500">No jobs found</p>
                    </div>
                )}
            </div>
        </div>
    );
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: number; icon: any; color: string }) {
    return (
        <div className="rounded-xl bg-white p-6 border border-slate-100 shadow-sm">
            <div className="flex items-center justify-between">
                <div>
                    <p className="text-sm font-medium text-slate-500">{label}</p>
                    <p className="text-3xl font-bold text-slate-900 mt-2">{value}</p>
                </div>
                <div className={`h-12 w-12 rounded-full ${color} opacity-10 flex items-center justify-center`}>
                    <Icon className={`h-6 w-6 ${color.replace('bg-', 'text-')}`} />
                </div>
            </div>
        </div>
    );
}
