import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { notFound, redirect } from "next/navigation";
import { MapPin, Briefcase, DollarSign, Clock, ArrowLeft, Edit, Users, LayoutTemplate } from "lucide-react";
import Link from "next/link";
import { JobStatusControl } from "@/components/jobs/JobStatusControl";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/Tabs";
import { JobAnalytics } from "@/components/jobs/JobAnalytics";
import dynamic from 'next/dynamic';

const JobDescriptionRenderer = dynamic(
    () => import('@/components/jobs/JobDescriptionRenderer').then(m => m.JobDescriptionRenderer),
    { ssr: false }
);

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

export default async function DashboardJobDetailsPage(props: PageProps) {
    const user = await getCurrentUser();

    if (!user) {
        redirect("/login");
    }

    const { id } = await props.params;

    // Validate UUID format to prevent Prisma errors
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    if (!uuidRegex.test(id)) {
        notFound();
    }

    const job = await prisma.job.findUnique({
        where: {
            id,
            employer_id: user.id
        },
        include: {
            skills: {
                include: { skill: true }
            }
        }
    });

    if (!job) {
        notFound();
    }

    const locationString = [job.city, job.state, job.country].filter(Boolean).join(", ") || "Remote";

    return (
        <div className="space-y-6">
            <Link
                href="/dashboard/jobs"
                className="inline-flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-primary transition-colors"
            >
                <ArrowLeft className="h-4 w-4" /> Back to My Jobs
            </Link>

            {/* Title & Actions */}
            <div className="flex flex-col md:flex-row md:items-start justify-between gap-4">
                <div className="flex items-center gap-4">
                    <div className="flex h-14 w-14 items-center justify-center rounded-xl bg-primary text-white text-2xl font-bold shadow-sm">
                        {job.company.charAt(0)}
                    </div>
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900">{job.title}</h1>
                        <p className="text-slate-500 font-medium">{job.company}</p>
                    </div>
                </div>

                <div className="flex items-center gap-3">
                    <span className={`inline-flex items-center px-3 py-1.5 rounded-full text-xs 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>

                    <Link
                        href={`/dashboard/jobs/${job.id}/edit`}
                        className="flex items-center gap-2 rounded-xl bg-white border border-slate-200 px-4 py-2 font-semibold text-slate-700 transition-colors hover:bg-slate-50 shadow-sm"
                    >
                        <Edit className="h-4 w-4" /> Edit
                    </Link>

                    <JobStatusControl jobId={job.id} currentStatus={job.status} />
                </div>
            </div>

            {/* Meta info row */}
            <div className="flex flex-wrap gap-5 text-sm font-medium text-slate-600 border-b border-slate-200 pb-6">
                <span className="flex items-center gap-1.5">
                    <MapPin className="h-4 w-4 text-slate-400" /> {locationString}
                </span>
                <span className="flex items-center gap-1.5">
                    <Briefcase className="h-4 w-4 text-slate-400" /> {job.type}
                </span>
                <span className="flex items-center gap-1.5">
                    <DollarSign className="h-4 w-4 text-slate-400" />
                    {job.salary_min ? `${job.currency} ${job.salary_min.toLocaleString()}` : 'N/A'} - {job.salary_max ? `${job.salary_max.toLocaleString()}` : ''}
                </span>
                <span className="flex items-center gap-1.5">
                    <Clock className="h-4 w-4 text-slate-400" /> Posted {new Date(job.posted_at).toLocaleDateString()}
                </span>
                <span className="flex items-center gap-1.5">
                    <Users className="h-4 w-4 text-slate-400" /> {job.applicant_count} applicant{job.applicant_count !== 1 ? 's' : ''}
                </span>
            </div>

            {/* Main Content - Tabs layout */}
            <Tabs defaultValue="details">
                <TabsList className="mb-6">
                    <TabsTrigger value="details">Job Details</TabsTrigger>
                    <TabsTrigger value="analytics">Analytics</TabsTrigger>
                </TabsList>

                <TabsContent value="details">
                    <div className="grid gap-8 lg:grid-cols-3">
                        <div className="lg:col-span-2 space-y-8">
                            {/* Job Description - rendered as HTML */}
                            <section>
                                <h2 className="text-lg font-bold text-slate-900 mb-4">Job Description</h2>
                                <JobDescriptionRenderer
                                    html={job.description || ''}
                                    className="prose prose-slate max-w-none text-slate-600"
                                />
                            </section>

                            {/* Requirements */}
                            {((job as any).requirements && (job as any).requirements.length > 0) && (
                                <section>
                                    <h2 className="text-lg font-bold text-slate-900 mb-4">Requirements</h2>
                                    <ul className="list-disc space-y-2 pl-5 text-slate-600">
                                        {((job as any).requirements as string[]).map((req: string, i: number) => (
                                            <li key={i}>{req}</li>
                                        ))}
                                    </ul>
                                </section>
                            )}
                        </div>

                        <div className="space-y-8">
                            {/* Skills */}
                            <section>
                                <h3 className="font-bold text-slate-900 mb-3">Required Skills</h3>
                                <div className="flex flex-wrap gap-2">
                                    {job.skills.map((s) => (
                                        <span key={s.skill.id} className="rounded-lg bg-slate-100 px-3 py-1.5 text-sm font-medium text-slate-600">
                                            {s.skill.name}
                                        </span>
                                    ))}
                                </div>
                            </section>

                            {/* Job Details */}
                            <section>
                                <h3 className="font-bold text-slate-900 mb-3">Job Details</h3>
                                <dl className="space-y-4 text-sm">
                                    <div>
                                        <dt className="text-slate-500 mb-1">Experience Level</dt>
                                        <dd className="font-medium text-slate-900 capitalize">{job.experience_level?.replace('_', ' ') || 'Not specified'}</dd>
                                    </div>
                                    <div>
                                        <dt className="text-slate-500 mb-1">Work Location</dt>
                                        <dd className="font-medium text-slate-900 capitalize">{job.work_location_type || 'Not specified'}</dd>
                                    </div>
                                </dl>
                            </section>
                        </div>
                    </div>
                </TabsContent>

                <TabsContent value="analytics">
                    <JobAnalytics jobId={job.id} />
                </TabsContent>
            </Tabs>
        </div>
    );
}
