import { notFound } from "next/navigation";
import { getCurrentUser } from "@/lib/auth";
import {
    FileText, Briefcase, MessageSquare, Video, Award,
    Activity, Sparkles, Calendar, Clock, Download, Users
} from "lucide-react";
import { getApplicationDetails } from "@/app/actions/applicationTracking";
import { markApplicationViewed } from "@/app/actions/employerDashboard";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/Tabs";
import { ApplicationHeader } from "@/components/applications/review/ApplicationHeader";
import { OverviewTab } from "@/components/applications/review/tabs/OverviewTab";
import { ActivityLogTab } from "@/components/applications/review/tabs/ActivityLogTab";
import { InterviewsTab } from "@/components/applications/review/tabs/InterviewsTab";
import { CandidateInterviewView } from "@/components/applications/review/CandidateInterviewView";
import { MessagesTab } from "@/components/applications/review/tabs/MessagesTab";
import { OfferTab } from "@/components/applications/review/tabs/OfferTab";
import { AIRecommendation } from "@/components/applications/review/AIRecommendation";
import { ExperienceTimeline } from "@/components/profile/ExperienceTimeline";
import { EducationList } from "@/components/profile/EducationList";
import { NotesPanel } from "@/components/applications/NotesPanel";
import { TeamComments } from "@/components/ats/TeamComments";
import { ActivityTimeline } from "@/components/ats/ActivityTimeline";
import { HiringTeamPanel } from "@/components/ats/HiringTeamPanel";

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

    let application;
    try {
        application = await getApplicationDetails(params.id);
    } catch (error) {
        notFound();
    }

    const { job, candidate, messages, interviews, offer, activities } = application;
    const profile = (candidate as any)?.profile;
    const isEmployer = currentUser.role === 'employer';

    // Mark as viewed (fire and forget)
    if (isEmployer) {
        try {
            await markApplicationViewed(params.id);
        } catch (error) {
            console.error(`Failed to mark application ${params.id} as viewed:`, error);
        }
    }

    // Experience/Education from profile
    const experience = profile?.experiences || (candidate as any)?.experience || [];
    const education = profile?.educations || (candidate as any)?.education || [];

    // Extract skill names for AI analysis
    const candidateSkills: string[] = ((candidate as any)?.skills || []).map(
        (s: any) => s.skill?.name || s.name || ""
    ).filter(Boolean);
    const jobSkills: string[] = ((job as any)?.skills || []).map(
        (s: any) => s.skill?.name || s.name || ""
    ).filter(Boolean);

    return (
        <div className="min-h-screen bg-slate-50/50 py-6">
            <div className="container mx-auto px-4 max-w-6xl space-y-6">
                {/* Application Header */}
                <ApplicationHeader
                    application={application}
                    candidate={candidate}
                    job={job}
                    isEmployer={isEmployer}
                />

                {/* Layout: Tabs + AI Recommendation sidebar for employers */}
                <div className={`grid gap-6 ${isEmployer ? "grid-cols-1 xl:grid-cols-4" : "grid-cols-1"}`}>
                    {/* Main Tabs Area */}
                    <div className={`${isEmployer ? "xl:col-span-3" : ""}`}>
                        <Tabs defaultValue="overview" className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden min-h-[500px]">
                            <TabsList className="px-2 pt-2 bg-slate-50/50">
                                <TabsTrigger value="overview" icon={<FileText className="w-4 h-4" />}>Overview</TabsTrigger>
                                <TabsTrigger value="job" icon={<Briefcase className="w-4 h-4" />}>Job Details</TabsTrigger>
                                <TabsTrigger value="messages" icon={<MessageSquare className="w-4 h-4" />}>Messages ({messages.length})</TabsTrigger>
                                <TabsTrigger value="interviews" icon={<Video className="w-4 h-4" />}>Interviews ({interviews.length})</TabsTrigger>
                                <TabsTrigger value="offer" icon={<Award className="w-4 h-4" />}>Offer {offer ? '(1)' : ''}</TabsTrigger>
                                <TabsTrigger value="activity" icon={<Activity className="w-4 h-4" />}>Activity</TabsTrigger>
                                {isEmployer && (
                                    <TabsTrigger value="team" icon={<Users className="w-4 h-4" />}>Team</TabsTrigger>
                                )}
                                {isEmployer && (
                                    <TabsTrigger value="timeline" icon={<Clock className="w-4 h-4" />}>Timeline</TabsTrigger>
                                )}
                            </TabsList>

                            <div className="p-6">
                                {/* Tab 1: Overview (NEW — enhanced) */}
                                <TabsContent value="overview">
                                    <OverviewTab
                                        application={application}
                                        candidate={candidate}
                                        job={job}
                                        isEmployer={isEmployer}
                                    />
                                </TabsContent>

                                {/* Tab 2: Job Details */}
                                <TabsContent value="job">
                                    <div className="max-w-3xl space-y-6">
                                        <h3 className="text-2xl font-bold text-slate-900">{job.title}</h3>
                                        <div className="flex flex-wrap gap-4 text-sm text-slate-600">
                                            <span className="flex items-center gap-1 bg-slate-100 px-3 py-1 rounded-full">
                                                <Briefcase className="w-4 h-4" /> {job.type}
                                            </span>
                                            <span className="flex items-center gap-1 bg-slate-100 px-3 py-1 rounded-full">
                                                <FileText className="w-4 h-4" /> {(job as any).department || (job as any).category || 'General'}
                                            </span>
                                            <span className="flex items-center gap-1 bg-slate-100 px-3 py-1 rounded-full">
                                                <Award className="w-4 h-4" /> Experience: {job.experience_level || 'Any'}
                                            </span>
                                        </div>
                                        {job.salary_min && job.salary_max && (
                                            <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-xl">
                                                <p className="text-sm font-bold text-emerald-900">
                                                    Salary: {job.currency || 'NGN'} {Number(job.salary_min).toLocaleString()} — {Number(job.salary_max).toLocaleString()}
                                                </p>
                                            </div>
                                        )}
                                        <div className="prose prose-slate max-w-none mt-4">
                                            <p className="whitespace-pre-line">{job.description}</p>
                                        </div>
                                    </div>
                                </TabsContent>

                                {/* Tab 3: Messages (Enhanced) */}
                                <TabsContent value="messages">
                                    <MessagesTab
                                        messages={messages}
                                        applicationId={application.id}
                                        currentUserId={currentUser.id}
                                    />
                                </TabsContent>

                                {/* Tab 4: Interviews (Enhanced) */}
                                <TabsContent value="interviews">
                                    {isEmployer ? (
                                        <InterviewsTab
                                            interviews={interviews}
                                            applicationId={application.id}
                                            jobTitle={job.title}
                                            candidateName={candidate.name || "Candidate"}
                                            isEmployer={isEmployer}
                                        />
                                    ) : (
                                        <CandidateInterviewView
                                            interviews={interviews}
                                            applicationId={application.id}
                                        />
                                    )}
                                </TabsContent>

                                {/* Tab 5: Offer (Interactive) */}
                                <TabsContent value="offer">
                                    <OfferTab
                                        offer={offer}
                                        applicationId={application.id}
                                        isEmployer={isEmployer}
                                    />
                                </TabsContent>

                                {/* Tab 6: Activity (legacy log) */}
                                <TabsContent value="activity">
                                    <ActivityLogTab
                                        activities={activities}
                                        application={application}
                                    />
                                </TabsContent>

                                {/* Tab 7: Team Discussion (employer only) */}
                                <TabsContent value="team">
                                    <TeamComments
                                        applicationId={application.id}
                                        currentUserId={currentUser.id}
                                    />
                                </TabsContent>

                                {/* Tab 8: Activity Timeline (employer only) */}
                                <TabsContent value="timeline">
                                    <ActivityTimeline applicationId={application.id} />
                                </TabsContent>
                            </div>
                        </Tabs>
                    </div>

                    {/* Sidebar: AI Recommendation & Notes (Employer only) */}
                    {isEmployer && (
                        <div className="xl:col-span-1 space-y-6">
                            <AIRecommendation
                                application={application}
                                job={job}
                                candidateSkills={candidateSkills}
                                jobSkills={jobSkills}
                            />
                            <HiringTeamPanel
                                jobId={job.id}
                                jobTitle={job.title}
                            />
                            <NotesPanel
                                applicationId={application.id}
                                currentUserId={currentUser.id}
                            />
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
