
import prisma from "@/lib/prisma";
import { notFound } from "next/navigation";
import { MapPin, Briefcase, DollarSign, Clock, ArrowLeft, PlayCircle, Eye } from "lucide-react";
import Link from "next/link";
import dynamic from 'next/dynamic';
import { JobViewTracker } from "@/components/jobs/JobViewTracker";

const JobDescriptionRenderer = dynamic(
    () => import('@/components/jobs/JobDescriptionRenderer').then(m => m.JobDescriptionRenderer),
    { ssr: false }
);
import { getCurrentUser } from "@/lib/auth";
import { ApplyButton } from "@/components/jobs/ApplyButton";

export const dynamic = "force-dynamic";

interface PageProps {
    params: Promise<{ id: string }>;
}

export default async function JobDetailsPage({ params }: PageProps) {
    const { id } = await params;

    // Fetch the Job using Prisma (includes relations if necessary)
    const job = await prisma.job.findUnique({
        where: { id },
        include: {
            employer: {
                select: {
                    profile: {
                        select: {
                            company_name: true,
                            company_logo_url: true,
                        }
                    }
                }
            },
            skills: {
                include: {
                    skill: true
                }
            }
        }
    });

    if (!job || job.status !== "published") {
        notFound();
    }

    const companyName = job.employer?.profile?.company_name || job.company || "Company";
    const skillList = job.skills?.map(s => s.skill.name) || [];

    const user = await getCurrentUser();
    let hasApplied = false;
    let defaultResumeUrl = null;

    if (user && user.role === "candidate") {
        // Check if user has already applied
        const existingApp = await prisma.application.findUnique({
            where: {
                job_id_candidate_id: {
                    job_id: job.id,
                    candidate_id: user.id
                }
            }
        });
        hasApplied = !!existingApp;

        // Get user's default resume
        const profile = await prisma.profile.findUnique({
            where: { user_id: user.id },
            select: { resume_url: true }
        });
        defaultResumeUrl = profile?.resume_url;
    }


    return (
        <div className="min-h-screen bg-slate-50 pb-20 pt-10">
            <JobViewTracker jobId={job.id} />
            <div className="container mx-auto max-w-4xl px-4">
                <Link
                    href="/"
                    className="mb-6 flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-primary"
                >
                    <ArrowLeft className="h-4 w-4" /> Back to Jobs
                </Link>

                {/* Header Card */}
                <div className="overflow-hidden rounded-2xl bg-white shadow-sm border border-slate-100">
                    <div className="bg-gradient-to-r from-blue-50 to-purple-50 p-8">
                        <div className="flex h-16 w-16 items-center justify-center rounded-xl bg-white text-2xl font-bold text-slate-500 shadow-sm">
                            {job.employer?.profile?.company_logo_url ? (
                                <img src={job.employer.profile.company_logo_url} alt={companyName} className="h-full w-full object-contain rounded-xl" />
                            ) : (
                                companyName.charAt(0).toUpperCase()
                            )}
                        </div>
                        <h1 className="mt-6 text-3xl font-bold text-slate-900">{job.title}</h1>
                        <p className="mt-2 text-lg text-slate-600">
                            {companyName} &bull; <span className="text-slate-500">{job.address || job.city || job.country || "Remote"}</span>
                        </p>
                    </div>

                    <div className="flex flex-wrap items-center justify-between gap-6 px-8 py-6">
                        <div className="flex flex-wrap gap-6 text-sm font-medium text-slate-600">
                            <span className="flex items-center gap-2 capitalize">
                                <Briefcase className="h-5 w-5 text-slate-400" /> {job.type.replace("-", " ")}
                            </span>
                            <span className="flex items-center gap-2">
                                <DollarSign className="h-5 w-5 text-slate-400" />
                                {job.salary_min ? `${job.currency === "NGN" ? "₦" : "$"}${job.salary_min.toLocaleString()}` : 'N/A'} {job.salary_max ? `- ${job.currency === "NGN" ? "₦" : "$"}${job.salary_max.toLocaleString()}` : ''}
                            </span>
                            <span className="flex items-center gap-2">
                                <Clock className="h-5 w-5 text-slate-400" /> Posted {new Date(job.posted_at).toLocaleDateString()}
                            </span>
                        </div>

                        <ApplyButton 
                            jobId={job.id} 
                            jobTitle={job.title} 
                            hasApplied={hasApplied} 
                            isAuthenticated={!!user} 
                            defaultResumeUrl={defaultResumeUrl} 
                        />
                    </div>
                </div>

                {/* Content Grid */}
                <div className="mt-8 grid gap-8 lg:grid-cols-3">
                    <div className="lg:col-span-2 space-y-8">
                        <section className="rounded-xl border border-slate-100 bg-white p-8 shadow-sm">
                            <h2 className="mb-4 text-xl font-bold text-slate-900">Description</h2>
                            <JobDescriptionRenderer
                                html={job.description || ''}
                                className="prose prose-slate max-w-none text-slate-600"
                            />
                        </section>

                        <section className="rounded-xl border border-slate-100 bg-white p-8 shadow-sm">
                            <h2 className="mb-4 text-xl font-bold text-slate-900">Requirements</h2>
                            <ul className="list-disc space-y-2 pl-5 text-slate-600">
                                {job.required_qualifications ? (job.required_qualifications as string[]).map((req, i) => (
                                    <li key={i}>{req}</li>
                                )) : (
                                    <li>No specific requirements listed.</li>
                                )}
                            </ul>
                        </section>
                    </div>

                    <div className="space-y-6">
                        <section className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm">
                            <h3 className="mb-4 font-bold text-slate-900">Required Skills</h3>
                            <div className="flex flex-wrap gap-2">
                                {skillList.length > 0 ? skillList.map(skill => (
                                    <span key={skill} className="rounded-lg bg-slate-50 px-3 py-1 text-sm font-medium text-slate-600">
                                        {skill}
                                    </span>
                                )) : (
                                    <p className="text-sm text-slate-500">Not specified</p>
                                )}
                            </div>
                        </section>

                        <section className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm">
                            <h3 className="mb-4 font-bold text-slate-900">About {companyName}</h3>
                            <p className="text-sm leading-relaxed text-slate-600">
                                {job.summary || `${companyName} is hiring a ${job.title}. Join the team to help build innovative solutions.`}
                            </p>
                        </section>
                    </div>
                </div>

            </div>
        </div>
    );
}
