import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { ViewToggle } from "@/components/shared/ViewToggle";
import { SearchFilter } from "@/components/shared/SearchFilter";
import { JobCard } from "@/components/jobs/JobCard";
import { JobsTable } from "@/components/jobs/JobsTable";
import Link from "next/link";
import { Plus } from "lucide-react";
import { redirect } from "next/navigation";


export default async function JobsPage(props: { searchParams: Promise<{ view?: string, q?: string }> }) {
    const user = await getCurrentUser();
    if (!user) {
        redirect("/login");
    }

    const searchParams = await props.searchParams;
    const view = searchParams.view || "grid";
    const query = searchParams.q?.toLowerCase() || "";

    // Fetch live jobs from Prisma for the current employer
    const prismaJobs = await prisma.job.findMany({
        where: { employer_id: user.id, deleted_at: null }, // Exclude soft-deleted jobs
        orderBy: { posted_at: 'desc' },
        include: {
            skills: {
                include: { skill: true }
            }
        }
    });

    const mappedJobs = prismaJobs.map(j => ({
        id: j.id,
        title: j.title,
        company: j.company,
        location: [j.city, j.state, j.country].filter(Boolean).join(", ") || "Remote",
        type: j.type, // e.g., "full-time"
        salaryMin: j.salary_min || undefined,
        salaryMax: j.salary_max || undefined,
        currency: j.currency,
        postedAt: j.posted_at.toISOString(),
        skills: j.skills.map(s => s.skill.name),
        status: j.status,
        applicants: j.applicant_count,
        experienceLevel: j.experience_level || undefined,
        workLocationType: j.work_location_type,
    }));

    // Filter Jobs
    const filteredJobs = mappedJobs.filter(job =>
        job.title.toLowerCase().includes(query) ||
        job.company.toLowerCase().includes(query) ||
        job.skills.some(skill => skill.toLowerCase().includes(query))
    );

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-slate-900">My Jobs</h1>
                    <p className="text-slate-500">Manage your job listings and view status.</p>
                </div>
                <div className="flex items-center gap-3">
                    <ViewToggle baseUrl="/dashboard/jobs" />
                    <Link
                        href="/dashboard/employer/post-job"
                        className="flex items-center gap-2 rounded-xl bg-primary px-4 py-2.5 text-sm font-bold text-white hover:bg-blue-700"
                    >
                        <Plus className="h-4 w-4" /> Post Job
                    </Link>
                </div>
            </div>

            {/* Filters */}
            <SearchFilter placeholder="Filter jobs by title, company, or skills..." />

            {/* Job List/Grid */}
            {view === "grid" ? (
                <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                    {filteredJobs.map((job) => (
                        <div key={job.id} className="relative">
                            <JobCard {...job} baseUrl="/dashboard/jobs" />

                            {/* Overlay tag for status */}
                            <div className="absolute top-2 right-2">
                                <span className={`inline-flex items-center px-2 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider ${job.status === 'published' ? 'bg-green-100 text-green-700' :
                                    job.status === 'pending' ? 'bg-amber-100 text-amber-700' :
                                        job.status === 'changes_requested' ? 'bg-red-100 text-red-700' :
                                            job.status === 'rejected' ? 'bg-red-200 text-red-800' :
                                                'bg-slate-100 text-slate-700'
                                    }`}>
                                    {job.status.replace('_', ' ')}
                                </span>
                            </div>

                            {/* Edit Button overlay if changes requested or draft */}
                            {(job.status === 'changes_requested' || job.status === 'draft') && (
                                <div className="absolute bottom-4 right-4 z-10">
                                    <Link href={`/dashboard/jobs/${job.id}/edit`} className="bg-red-600 hover:bg-red-700 text-white text-xs px-3 py-1.5 rounded shadow-sm font-medium">
                                        Edit to Resubmit
                                    </Link>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            ) : (
                <JobsTable jobs={filteredJobs} baseUrl="/dashboard/jobs" />
            )}
        </div>
    );
}
