import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";
import { CandidateProfileEditForm } from "@/components/profile/CandidateProfileEditForm";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function EditProfilePage() {
    const currentUser = await getCurrentUser();
    if (!currentUser) redirect("/login");
    if (currentUser.role !== "candidate") redirect("/dashboard");

    const [profile, userSkills, experiences, educationList] = await Promise.all([
        prisma.profile.findUnique({ where: { user_id: currentUser.id } }),
        prisma.userSkill.findMany({
            where: { user_id: currentUser.id },
            include: { skill: true },
        }),
        prisma.experience.findMany({
            where: { user_id: currentUser.id },
            orderBy: { start_date: "desc" },
        }),
        prisma.education.findMany({
            where: { user_id: currentUser.id },
            orderBy: { end_date: "desc" },
        }),
    ]);

    const skillNames = userSkills.map((us) => us.skill.name);

    return (
        <div className="space-y-6 max-w-5xl mx-auto">
            {/* Header */}
            <div className="flex items-center gap-4">
                <Link
                    href="/dashboard/profile/view"
                    className="flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-primary transition-colors group"
                >
                    <span className="w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center group-hover:border-primary/40 group-hover:bg-primary/5 transition-all">
                        <ArrowLeft className="h-4 w-4" />
                    </span>
                    Back to Profile
                </Link>
            </div>

            <div>
                <h1 className="text-2xl font-bold text-slate-900">Edit Profile</h1>
                <p className="text-slate-500 mt-1 text-sm">
                    Keep your profile up to date to attract the right opportunities.
                </p>
            </div>

            <CandidateProfileEditForm
                profile={profile}
                skillNames={skillNames}
                experiences={experiences}
                educationList={educationList}
                userName={currentUser.name || ""}
                avatarUrl={currentUser.avatarUrl || ""}
            />
        </div>
    );
}
