"use server";

import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import { Prisma } from "@prisma/client";
import { triggerStageAutomations } from "./transitionRuleActions";

const DEFAULT_STAGES = [
    { name: "Applied", color: "#94a3b8" }, // slate-400
    { name: "Screening", color: "#3b82f6" }, // blue-500
    { name: "Interview", color: "#8b5cf6" }, // violet-500
    { name: "Assessment", color: "#f59e0b" }, // amber-500
    { name: "Offer", color: "#10b981" }, // emerald-500
    { name: "Hired", color: "#059669" }, // emerald-600
    { name: "Rejected", color: "#ef4444" }, // red-500
];

export async function getOrCreatePipeline(jobId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        // Verify job belongs to employer
        const job = await prisma.job.findUnique({
            where: { id: jobId, employer_id: user.id },
            select: { id: true, title: true }
        });

        if (!job) {
            return { success: false, error: "Job not found" };
        }

        // Check if pipeline exists
        let pipeline = await prisma.hiringPipeline.findUnique({
            where: { job_id: jobId },
            include: {
                stages: {
                    orderBy: { order: 'asc' },
                    include: {
                        applications: {
                            include: {
                                candidate: {
                                    select: {
                                        id: true,
                                        name: true,
                                        avatar_url: true,
                                        first_name: true,
                                        last_name: true,
                                        profile: { select: { headline: true } }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });

        // If no pipeline, create default one
        if (!pipeline) {
            pipeline = await prisma.hiringPipeline.create({
                data: {
                    employer_id: user.id,
                    job_id: jobId,
                    name: `Pipeline: ${job.title}`,
                    is_default: true,
                    stages: {
                        create: DEFAULT_STAGES.map((stage, index) => ({
                            name: stage.name,
                            color: stage.color,
                            order: index
                        }))
                    }
                },
                include: {
                    stages: {
                        orderBy: { order: 'asc' },
                        include: {
                            applications: {
                                include: {
                                    candidate: {
                                        select: {
                                            id: true,
                                            name: true,
                                            avatar_url: true,
                                            first_name: true,
                                            last_name: true,
                                            profile: {
                                                select: { headline: true }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });

            // Move existing applications to the first stage
            const firstStage = pipeline.stages[0];
            if (firstStage) {
                // Get all unassigned applications for this job
                const unassignedApps = await prisma.application.findMany({
                    where: { job_id: jobId, current_stage_id: null },
                    select: { id: true }
                });

                if (unassignedApps.length > 0) {
                    await prisma.application.updateMany({
                        where: { id: { in: unassignedApps.map(a => a.id) } },
                        data: { current_stage_id: firstStage.id }
                    });

                    // Create history records
                    await prisma.candidateStageHistory.createMany({
                        data: unassignedApps.map(app => ({
                            application_id: app.id,
                            stage_id: firstStage.id,
                            actor_id: user.id,
                            notes: "Auto-assigned to initial stage",
                        }))
                    });

                    // Refetch pipeline to get updated applications
                    pipeline = await prisma.hiringPipeline.findUnique({
                        where: { job_id: jobId },
                        include: {
                            stages: {
                                orderBy: { order: 'asc' },
                                include: {
                                    applications: {
                                        include: {
                                            candidate: {
                                                select: {
                                                    id: true,
                                                    name: true,
                                                    avatar_url: true,
                                                    first_name: true,
                                                    last_name: true,
                                                    profile: {
                                                        select: { headline: true }
                                                    }
                                                }
                                            },
                                            application_tags: {
                                                include: { tag: true }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        }

        return { success: true, pipeline };
    } catch (error) {
        console.error("Failed to get/create pipeline:", error);
        return { success: false, error: "Internal server error" };
    }
}

export async function moveApplicationStage(applicationId: string, newStageId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: { job: true }
        });

        if (!application || application.job.employer_id !== user.id) {
            return { success: false, error: "Application not found" };
        }

        const newStage = await prisma.hiringStage.findUnique({
            where: { id: newStageId }
        });

        if (!newStage) {
            return { success: false, error: "Stage not found" };
        }

        // Close out previous history if exists
        const currentStageHistory = await prisma.candidateStageHistory.findFirst({
            where: {
                application_id: applicationId,
                stage_id: application.current_stage_id || undefined,
                left_at: null
            },
            orderBy: { entered_at: 'desc' }
        });

        if (currentStageHistory) {
            const now = new Date();
            const durationMs = now.getTime() - currentStageHistory.entered_at.getTime();
            const durationDays = Math.floor(durationMs / (1000 * 60 * 60 * 24));

            await prisma.candidateStageHistory.update({
                where: { id: currentStageHistory.id },
                data: {
                    left_at: now,
                    duration_days: durationDays
                }
            });
        }

        // Add new history record
        await prisma.candidateStageHistory.create({
            data: {
                application_id: applicationId,
                stage_id: newStageId,
                actor_id: user.id
            }
        });

        // Update application
        await prisma.application.update({
            where: { id: applicationId },
            data: { current_stage_id: newStageId }
        });

        // Trigger stage automations asynchronously (don't block the UI response)
        triggerStageAutomations(applicationId, newStageId).catch(console.error);

        revalidatePath(`/dashboard/jobs/${application.job_id}`);
        revalidatePath('/dashboard/applications');

        return { success: true };
    } catch (error) {
        console.error("Failed to move application:", error);
        return { success: false, error: "Internal server error" };
    }
}

export async function getPipelineAnalytics(jobId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const job = await prisma.job.findUnique({
            where: { id: jobId, employer_id: user.id },
            select: { id: true }
        });

        if (!job) {
            return { success: false, error: "Job not found" };
        }

        const pipeline = await prisma.hiringPipeline.findUnique({
            where: { job_id: jobId },
            include: {
                stages: {
                    orderBy: { order: 'asc' },
                    include: {
                        _count: { select: { applications: true } },
                        history: {
                            where: { left_at: { not: null } },
                            select: { duration_days: true }
                        }
                    }
                }
            }
        });

        if (!pipeline) {
            return { success: false, error: "Pipeline not found" };
        }

        // Funnel & Drop-off Stats
        const funnelStats = [];
        let previousStageCount = 0;

        for (let i = 0; i < pipeline.stages.length; i++) {
            const stage = pipeline.stages[i];

            // Time in stage calculation
            let avgTimeInStage = 0;
            if (stage.history.length > 0) {
                const totalDays = stage.history.reduce((sum, h) => sum + (h.duration_days || 0), 0);
                avgTimeInStage = Math.round((totalDays / stage.history.length) * 10) / 10;
            }

            // Historical total entering this stage (active + moved past this + rejected from this)
            // Simplified for now based on current counts, but true funnel requires reading all history.
            // A more exact funnel requires tracking historically how many applications touched this stage_id.
            const totalEntered = await prisma.candidateStageHistory.groupBy({
                by: ['application_id'],
                where: { stage_id: stage.id, application: { job_id: jobId } },
            }).then(res => res.length);

            // Drop-off Calculation:
            // How many left this stage specifically to 'Rejected'
            // We find "Rejected" stage if it exists.
            const rejectedStage = pipeline.stages.find(s => s.name.toLowerCase().includes('reject'));

            let dropOffRate = 0;
            if (rejectedStage && stage.id !== rejectedStage.id) {
                // Count applications currently in "Rejected" that came directly from this stage
                // Or historically went from this stage -> rejected. 
                // For true accuracy, we'd need complex queries. We'll simulate dropOff for now by comparing `totalEntered` with next stage's `totalEntered`.
                const nextStage = pipeline.stages[i + 1];
                if (nextStage && totalEntered > 0) {
                    const nextStageEntered = await prisma.candidateStageHistory.groupBy({
                        by: ['application_id'],
                        where: { stage_id: nextStage.id, application: { job_id: jobId } },
                    }).then(res => res.length);

                    dropOffRate = Math.round(((totalEntered - nextStageEntered) / totalEntered) * 100);
                }
            }

            let conversionRate = 100;
            if (i > 0 && previousStageCount > 0) {
                conversionRate = Math.round((totalEntered / previousStageCount) * 100);
            }
            previousStageCount = totalEntered;

            funnelStats.push({
                stageId: stage.id,
                name: stage.name,
                color: stage.color,
                activeCount: stage._count.applications,
                totalEntered,
                conversionRate: i === 0 ? 100 : conversionRate,
                dropOffRate: Math.max(0, dropOffRate),
                avgTimeInStage
            });
        }

        // Overall stats
        const totalApplications = await prisma.application.count({ where: { job_id: jobId } });

        // Find "Hired" or end-stage conversion
        const hiredStage = pipeline.stages.find(s => s.name.toLowerCase() === 'hired');
        let totalHired = 0;
        if (hiredStage) {
            totalHired = hiredStage._count.applications;
        }

        const overallConversion = totalApplications > 0 ? Math.round((totalHired / totalApplications) * 100) : 0;

        return {
            success: true,
            data: {
                totalApplications,
                totalHired,
                overallConversion,
                funnel: funnelStats
            }
        };

    } catch (error) {
        console.error("Failed to get pipeline analytics:", error);
        return { success: false, error: "Internal server error" };
    }
}
