import { getCurrentUser } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { redirect } from "next/navigation";
import { ProfileHeader } from "@/components/profile/ProfileHeader";
import { Briefcase, GraduationCap, FileText, Link2, Github, Linkedin, Globe, Award, Target, Languages, HeartHandshake, BookOpen } from "lucide-react";
import Link from "next/link";
import { format } from "date-fns";
import * as motion from "framer-motion/client";

export default async function ViewProfilePage() {
    const sessionUser = await getCurrentUser();

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

    if (sessionUser.role !== "candidate" && sessionUser.role !== "employer") {
        redirect("/dashboard");
    }

    // Fetch the FULL user profile from Prisma
    const user = await prisma.user.findUnique({
        where: { id: sessionUser.id },
        include: {
            profile: true,
            skills: { include: { skill: true } },
            experiences: { orderBy: { start_date: 'desc' } },
            education: { orderBy: { end_date: 'desc' } },
            certifications: { orderBy: { issue_date: 'desc' } },
            projects: { orderBy: { start_date: 'desc' } },
            awards: { orderBy: { date: 'desc' } },
            languages: true,
            publications: { orderBy: { date: 'desc' } },
            volunteer_experiences: { orderBy: { start_date: 'desc' } }
        }
    });

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

    // Prepare data
    const experiences = user.experiences || [];
    const educations = user.education || [];
    const skills = user.skills.map(s => s.skill.name) || [];

    // New Extended Models
    const certifications = user.certifications || [];
    const projects = user.projects || [];
    const awards = user.awards || [];
    const languages = user.languages || [];
    const publications = user.publications || [];
    const volunteerExp = user.volunteer_experiences || [];

    return (
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4 }}
            className="space-y-6 max-w-5xl mx-auto pb-12"
        >
            <ProfileHeader user={user} isOwnProfile={true} />

            {/* Conditional Content based on Role */}
            {sessionUser.role === "employer" ? (
                /* EMPLOYER / COMPANY PROFILE VIEW */
                <div className="space-y-6">
                    {/* About Company */}
                    <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1 }}
                        className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                    >
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="text-xl font-bold text-slate-900">About {user.profile?.company_name || 'the Company'}</h2>
                            <Link href="/dashboard/profile/edit#about" className="text-sm font-medium text-primary hover:text-primary/80 transition-colors">
                                Edit
                            </Link>
                        </div>
                        {user.profile?.company_description ? (
                            <p className="text-slate-700 leading-relaxed whitespace-pre-line">{user.profile.company_description}</p>
                        ) : (
                            <p className="text-slate-500 italic">No company description provided.</p>
                        )}
                    </motion.div>

                    {/* Company Details Grid */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.2 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <h2 className="text-xl font-bold text-slate-900 mb-4">Company Details</h2>
                            <div className="space-y-4">
                                <div>
                                    <p className="text-sm text-slate-500 font-medium">Industry</p>
                                    <p className="text-slate-900 font-medium">{user.profile?.company_industry || "Not specified"}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-slate-500 font-medium">Company Size</p>
                                    <p className="text-slate-900 font-medium">{user.profile?.company_size || "Not specified"}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-slate-500 font-medium">Location</p>
                                    <p className="text-slate-900 font-medium">{user.profile?.location || "Not specified"}</p>
                                </div>
                            </div>
                        </motion.div>
                    </div>
                </div>
            ) : (
                /* CANDIDATE PROFILE VIEW */
                <div className="space-y-6">
                    {/* About Me Section */}
                    {user.profile?.about_me && (
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.1 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <h2 className="text-xl font-bold text-slate-900 mb-4">About</h2>
                            <p className="text-slate-700 leading-relaxed whitespace-pre-line">{user.profile.about_me}</p>
                        </motion.div>
                    )}

                    {/* Work Experience Section */}
                    <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.2 }}
                        className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                    >
                        <div className="flex items-center justify-between mb-6 border-b border-slate-50 pb-4">
                            <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                <Briefcase className="h-5 w-5 text-primary" />
                                Experience
                            </h2>
                            <Link href="/dashboard/profile/edit#experience" className="text-sm font-medium text-primary hover:text-primary/80 transition-colors">
                                Edit
                            </Link>
                        </div>

                        {experiences.length === 0 ? (
                            <div className="text-center py-8">
                                <Briefcase className="h-12 w-12 text-slate-200 mx-auto mb-3" />
                                <p className="text-slate-500 font-medium">No experience added yet</p>
                                <p className="text-sm text-slate-400 mt-1 mb-4">Showcase your professional background</p>
                                <Link href="/dashboard/profile/edit#experience" className="inline-flex items-center justify-center px-4 py-2 rounded-lg bg-primary/10 text-primary font-medium hover:bg-primary/20 transition-colors">
                                    Add Experience
                                </Link>
                            </div>
                        ) : (
                            <div className="space-y-8">
                                {experiences.map((exp: any, index: number) => (
                                    <div key={exp.id} className={`relative pl-8 ${index !== experiences.length - 1 ? 'pb-8' : ''}`}>
                                        {index !== experiences.length - 1 && (
                                            <div className="absolute left-2.5 top-8 bottom-0 w-px bg-slate-200" />
                                        )}
                                        <div className="absolute left-0 top-1.5 w-5 h-5 rounded-full bg-primary/20 border-[3px] border-white shadow-sm flex items-center justify-center">
                                            <div className="w-2 h-2 rounded-full bg-primary" />
                                        </div>
                                        <div>
                                            <h3 className="font-bold text-slate-900 text-lg">{exp.title}</h3>
                                            <p className="text-primary font-medium">{exp.company}</p>
                                            <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-1 text-sm text-slate-500">
                                                <span>
                                                    {format(new Date(exp.start_date), 'MMM yyyy')} - {' '}
                                                    {exp.is_current ? 'Present' : (exp.end_date ? format(new Date(exp.end_date), 'MMM yyyy') : '')}
                                                </span>
                                                {exp.location && <span>• {exp.location}</span>}
                                            </div>
                                            {exp.description && (
                                                <p className="text-slate-600 mt-3 text-sm leading-relaxed whitespace-pre-line">{exp.description}</p>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </motion.div>

                    {/* Education Section */}
                    <motion.div
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.3 }}
                        className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                    >
                        <div className="flex items-center justify-between mb-6 border-b border-slate-50 pb-4">
                            <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                <GraduationCap className="h-5 w-5 text-primary" />
                                Education
                            </h2>
                            <Link href="/dashboard/profile/edit#education" className="text-sm font-medium text-primary hover:text-primary/80 transition-colors">
                                Edit
                            </Link>
                        </div>

                        {educations.length === 0 ? (
                            <div className="text-center py-8">
                                <GraduationCap className="h-12 w-12 text-slate-200 mx-auto mb-3" />
                                <p className="text-slate-500 font-medium">No education added yet</p>
                                <Link href="/dashboard/profile/edit#education" className="mt-4 inline-flex items-center justify-center px-4 py-2 rounded-lg bg-primary/10 text-primary font-medium hover:bg-primary/20 transition-colors">
                                    Add Education
                                </Link>
                            </div>
                        ) : (
                            <div className="space-y-8">
                                {educations.map((edu: any, index: number) => (
                                    <div key={edu.id} className={`relative pl-8 ${index !== educations.length - 1 ? 'pb-8' : ''}`}>
                                        {index !== educations.length - 1 && (
                                            <div className="absolute left-2.5 top-8 bottom-0 w-px bg-slate-200" />
                                        )}
                                        <div className="absolute left-0 top-1.5 w-5 h-5 rounded-full bg-slate-200 border-[3px] border-white shadow-sm flex items-center justify-center">
                                            <div className="w-2 h-2 rounded-full bg-slate-400" />
                                        </div>
                                        <div>
                                            <h3 className="font-bold text-slate-900 text-lg">{edu.degree} {edu.field ? `in ${edu.field}` : ''}</h3>
                                            <p className="text-slate-800 font-medium">{edu.institution}</p>
                                            <p className="text-sm text-slate-500 mt-1">
                                                {edu.start_date ? format(new Date(edu.start_date), 'yyyy') : ''} - {' '}
                                                {edu.end_date ? format(new Date(edu.end_date), 'yyyy') : 'Present'}
                                            </p>
                                            {edu.description && (
                                                <p className="text-slate-600 mt-2 text-sm leading-relaxed whitespace-pre-line">{edu.description}</p>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </motion.div>

                    {/* Grid for Smaller Sections */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

                        {/* Skills Section */}
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.4 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <div className="flex items-center justify-between mb-4">
                                <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                    <Target className="h-5 w-5 text-primary" />
                                    Skills
                                </h2>
                            </div>
                            {skills.length === 0 ? (
                                <p className="text-slate-500 text-sm">No skills added yet</p>
                            ) : (
                                <div className="flex flex-wrap gap-2">
                                    {skills.map((skill: string) => (
                                        <span
                                            key={skill}
                                            className="px-3 py-1.5 bg-slate-100 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-200 transition-colors"
                                        >
                                            {skill}
                                        </span>
                                    ))}
                                </div>
                            )}
                        </motion.div>

                        {/* Languages Section */}
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.45 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <div className="flex items-center justify-between mb-4">
                                <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                    <Languages className="h-5 w-5 text-primary" />
                                    Languages
                                </h2>
                                <Link href="/dashboard/profile/edit#languages" className="text-sm font-medium text-primary hover:text-primary/80 transition-colors">
                                    Edit
                                </Link>
                            </div>
                            {languages.length === 0 ? (
                                <p className="text-slate-500 text-sm">No languages added yet</p>
                            ) : (
                                <div className="space-y-3">
                                    {languages.map((lang: any) => (
                                        <div key={lang.id} className="flex items-center justify-between">
                                            <span className="font-medium text-slate-800">{lang.name}</span>
                                            <span className="text-xs font-semibold px-2 py-1 bg-primary/10 text-primary rounded-full">
                                                {lang.proficiency}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </motion.div>
                    </div>

                    {/* Certifications & Awards Grid */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {/* Certifications */}
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.5 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <div className="flex items-center justify-between mb-6">
                                <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                    <Award className="h-5 w-5 text-primary" />
                                    Certifications
                                </h2>
                            </div>
                            {certifications.length === 0 ? (
                                <p className="text-slate-500 text-sm">No certifications added yet</p>
                            ) : (
                                <div className="space-y-4">
                                    {certifications.map((cert: any) => (
                                        <div key={cert.id} className="border-b border-slate-50 last:border-0 pb-4 last:pb-0">
                                            <h3 className="font-bold text-slate-900">{cert.name}</h3>
                                            <p className="text-sm text-slate-600">{cert.organization}</p>
                                            <p className="text-xs text-slate-400 mt-1">
                                                Issued {cert.issue_date ? format(new Date(cert.issue_date), 'MMM yyyy') : ''}
                                            </p>
                                            {cert.credential_url && (
                                                <a href={cert.credential_url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 mt-2 text-xs font-medium text-primary hover:underline">
                                                    View Credential <Link2 className="h-3 w-3" />
                                                </a>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </motion.div>

                        {/* Projects */}
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.55 }}
                            className="bg-white rounded-2xl border border-slate-100 p-6 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.1)]"
                        >
                            <div className="flex items-center justify-between mb-6">
                                <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
                                    <BookOpen className="h-5 w-5 text-primary" />
                                    Projects
                                </h2>
                            </div>
                            {projects.length === 0 ? (
                                <p className="text-slate-500 text-sm">No projects added yet</p>
                            ) : (
                                <div className="space-y-4">
                                    {projects.map((project: any) => (
                                        <div key={project.id} className="border-b border-slate-50 last:border-0 pb-4 last:pb-0">
                                            <h3 className="font-bold text-slate-900">{project.title}</h3>
                                            {project.role && <p className="text-sm font-medium text-slate-600">{project.role}</p>}
                                            {project.description && <p className="text-sm text-slate-500 mt-1 line-clamp-2">{project.description}</p>}
                                            {project.url && (
                                                <a href={project.url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 mt-2 text-xs font-medium text-primary hover:underline">
                                                    View Project <Link2 className="h-3 w-3" />
                                                </a>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </motion.div>
                    </div>
                </div>
            )}
        </motion.div>
    );
}
