import { StandardApplicationForm } from "@/components/applications/StandardApplicationForm";
import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";

export default async function ApplyPage(props: { params: Promise<{ id: string }> }) {
    const params = await props.params;
    const currentUser = await getCurrentUser();

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

    if (currentUser.role !== 'candidate') {
        redirect("/dashboard"); // Only candidates can apply
    }

    // Fetch Job
    const job = await prisma.job.findUnique({
        where: { id: params.id }
    });

    if (!job) {
        notFound();
    }

    // Fetch Candidate Profile
    const candidateProfile = await prisma.profile.findUnique({
        where: { user_id: currentUser.id },
        include: { user: true }
    });

    return (
        <div className="min-h-screen bg-slate-50/50 flex flex-col items-center justify-center py-10 px-4">
            <div className="w-full max-w-2xl mb-6 flex items-center justify-between">
                <Link
                    href={`/jobs/${job.id}`}
                    className="inline-flex items-center gap-2 text-sm font-bold text-slate-500 hover:text-slate-900 transition-colors"
                >
                    <ArrowLeft className="h-4 w-4" /> Back to Job Details
                </Link>
            </div>

            <StandardApplicationForm
                jobId={job.id}
                jobTitle={job.title}
                companyName={job.company}
                candidateId={currentUser.id}
                candidateProfile={candidateProfile || { user: currentUser }}
            />
        </div>
    );
}
