import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { ApplicationsTable } from "@/components/dashboard/ApplicationsTable";
import { CandidateDashboard } from "@/components/dashboard/CandidateDashboard";
import { StatsCards, ApplicantSourcesWidget, ScheduleWidget, TaskProgressWidget } from "@/components/dashboard/DashboardWidgets";
import {
    CompanyProfileWidget,
    HiringMetricsWidget,
    ApplicantPipelineWidget,
    QuickPostJobWidget,
    JobPerformanceWidget
} from "@/components/dashboard/widgets/EmployerWidgets";
import { db, User } from "@/lib/db";
import prisma from "@/lib/prisma";
import { calculateCandidateCompletion, calculateEmployerCompletion } from "@/lib/profile-completion";
import { getRecommendedJobs } from "@/lib/recommendations";

export default async function DashboardPage() {
    const currentUser = await getCurrentUser();
    if (!currentUser) redirect("/login");

    // ─── Candidate dashboard ────────────────────────────────────────────
    if (currentUser.role === "candidate") {
        // Fetch real profile data in parallel
        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 } }),
            prisma.education.findMany({ where: { user_id: currentUser.id } }),
        ]);

        const skillNames = userSkills.map((us) => us.skill.name);
        const completion = calculateCandidateCompletion(
            profile,
            skillNames.length,
            experiences.length,
            educationList.length,
            !!currentUser.avatarUrl
        );

        // Real skill-based recommendations
        const { jobs } = await db.read();
        const recommendations = await getRecommendedJobs(
            { ...currentUser, skills: skillNames } as User
        );

        // Saved jobs from local db (until fully migrated to Prisma)
        const savedJobIds = currentUser.savedJobIds || [];
        const savedJobs = jobs.filter((job) => savedJobIds.includes(job.id));

        // ── Real application & interview counts from Prisma ──
        const [candidateApps, upcomingInterviews] = await Promise.all([
            prisma.application.findMany({
                where: { candidate_id: currentUser.id },
                include: {
                    job: { select: { title: true, company: true } },
                    interviews: {
                        where: {
                            status: { in: ["scheduled", "confirmed"] },
                            scheduled_start_datetime: { gte: new Date() },
                        },
                        orderBy: { scheduled_start_datetime: "asc" },
                        take: 3,
                        select: {
                            id: true,
                            title: true,
                            type: true,
                            status: true,
                            scheduled_start_datetime: true,
                            video_conference_link: true,
                        },
                    },
                },
                orderBy: { applied_at: "desc" },
            }),
            prisma.interview.findMany({
                where: {
                    application: { candidate_id: currentUser.id },
                    status: { in: ["scheduled", "confirmed"] },
                    scheduled_start_datetime: { gte: new Date() },
                },
                include: {
                    job: { select: { title: true, company: true } },
                },
                orderBy: { scheduled_start_datetime: "asc" },
                take: 3,
            }),
        ]);

        // Count applications by status
        const candidateStats = {
            totalApplications: candidateApps.length,
            inReview: candidateApps.filter(a => ["pending", "reviewing"].includes(a.status)).length,
            interviewing: candidateApps.filter(a => a.status === "interview").length,
            offered: candidateApps.filter(a => a.status === "offered").length,
            rejected: candidateApps.filter(a => a.status === "rejected").length,
        };

        // Map real applications for JobProgress
        const recentApps = candidateApps.slice(0, 4).map(app => ({
            id: app.id,
            company: app.job.company,
            role: app.job.title,
            status: app.status,
            date: app.applied_at.toISOString(),
        }));

        return (
            <CandidateDashboard
                user={{ ...currentUser, skills: skillNames }}
                recommendations={recommendations}
                savedJobs={savedJobs}
                profileCompletion={completion.score}
                completionTips={completion.tips}
                stats={candidateStats}
                recentApplications={recentApps}
                upcomingInterviews={upcomingInterviews.map(iv => ({
                    id: iv.id,
                    title: iv.job.title,
                    company: iv.job.company,
                    type: iv.type,
                    scheduledAt: iv.scheduled_start_datetime.toISOString(),
                    videoLink: iv.video_conference_link || undefined,
                }))}
            />
        );
    }

    // ─── Employer / Admin dashboard ─────────────────────────────────────
    
    // Fetch real Prisma applications for this employer's jobs
    const employerJobs = await prisma.job.findMany({
        where: { employer_id: currentUser.id },
        select: { id: true },
    });
    const employerJobIds = employerJobs.map(j => j.id);

    const [prismaApplications, employerProfile] = await Promise.all([
        prisma.application.findMany({
            where: { job_id: { in: employerJobIds } },
            include: {
                job: { select: { title: true, company: true, view_count: true } },
                candidate: { select: { id: true, first_name: true, last_name: true, name: true, email: true } },
            },
            orderBy: { applied_at: "desc" },
        }),
        prisma.profile.findUnique({ where: { user_id: currentUser.id } }),
    ]);

    const employerCompletion = calculateEmployerCompletion(
        employerProfile,
        !!employerProfile?.company_logo_url
    );

    // Pipeline counts from real Prisma data
    const pipelineCounts = {
        total: prismaApplications.length,
        pending: prismaApplications.filter(a => a.status === "pending").length,
        reviewing: prismaApplications.filter(a => a.status === "reviewing").length,
        interview: prismaApplications.filter(a => a.status === "interview").length,
        offered: prismaApplications.filter(a => a.status === "offered").length,
        rejected: prismaApplications.filter(a => a.status === "rejected").length,
    };

    // Build recent applications table data purely from Prisma
    const recentApplications = prismaApplications.slice(0, 5).map(app => ({
        id: app.id,
        candidateName: [app.candidate.first_name, app.candidate.last_name].filter(Boolean).join(" ") || app.candidate.name || "Unknown",
        email: app.candidate.email,
        role: app.job.title,
        status: app.status as any,
        appliedAt: app.applied_at.toISOString(),
        avatar: ((app.candidate.first_name || app.candidate.name || "U").charAt(0) + (app.candidate.last_name || "").charAt(0)).substring(0, 2),
        cvLink: app.cv_link || app.resume_url || undefined,
    }));

    // Personalize welcome message
    const companyName = employerProfile?.company_name;
    const welcomeName = currentUser.firstName || currentUser.name || "Admin";

    // Compute total job views for this employer
    const totalJobViews = prismaApplications.reduce((acc, app) => acc + (app.job.view_count || 0), 0);

    return (
        <div className="space-y-6">
            {/* Welcome Banner */}
            <section className="rounded-3xl bg-gradient-to-br from-slate-900 to-slate-800 p-8 text-white shadow-xl lg:p-10 relative overflow-hidden flex flex-col md:flex-row md:items-center justify-between gap-6">
                <div className="absolute right-0 top-0 w-1/3 h-full bg-gradient-to-l from-white/10 to-transparent skew-x-12 transform -translate-x-10" />
                <div className="relative z-10 max-w-2xl">
                    <h1 className="text-3xl font-bold lg:text-4xl text-white">
                        Welcome back, {welcomeName}! 🚀
                    </h1>
                    <p className="mt-4 text-lg text-slate-300">
                        {companyName
                            ? `Here's your recruitment overview for ${companyName}.`
                            : "Here's a summary of your recruitment pipeline and team activity today."}
                    </p>
                </div>
                <div className="relative z-10 bg-white/10 backdrop-blur-md border border-white/20 p-5 rounded-2xl md:w-80">
                    <p className="text-sm font-semibold text-slate-200 mb-2">Need to hire quickly?</p>
                    <a href="/dashboard/employer/post-job" className="block w-full bg-white text-slate-900 font-bold py-2.5 rounded-lg shadow-sm hover:scale-[1.02] transition-transform text-center">
                        Create Job Post
                    </a>
                </div>
            </section>

            {/* Overview Stats */}
            <section>
                <StatsCards applications={prismaApplications} />
            </section>

            <div className="grid gap-6 lg:grid-cols-3 xl:grid-cols-4">
                {/* Left Column - Main Activity */}
                <div className="lg:col-span-2 xl:col-span-3 space-y-6">
                    <div className="grid gap-6 md:grid-cols-2">
                        <ApplicantPipelineWidget pipeline={pipelineCounts} />
                        <HiringMetricsWidget pipeline={pipelineCounts} totalViews={totalJobViews} />
                    </div>
                    <ApplicationsTable applications={recentApplications} />
                    <div className="grid gap-6 md:grid-cols-2">
                        <JobPerformanceWidget />
                        <ApplicantSourcesWidget />
                    </div>
                </div>

                {/* Right Column - Contextual Widgets */}
                <div className="lg:col-span-1 xl:col-span-1 space-y-6">
                    <CompanyProfileWidget
                        completion={employerCompletion.score}
                        companyName={employerProfile?.company_name || undefined}
                        industry={employerProfile?.company_industry || undefined}
                    />
                    <QuickPostJobWidget />
                    <ScheduleWidget />
                    <TaskProgressWidget />
                </div>
            </div>
        </div>
    );
}
