"use server";

import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

// ─── Timeline Event Type ────────────────────────────────
export interface TimelineEvent {
    id: string;
    type: "stage_change" | "interview" | "feedback" | "note" | "message" | "activity" | "offer" | "comment" | "tag" | "score";
    title: string;
    description?: string;
    actor?: { id: string; name: string; avatar_url?: string | null };
    metadata?: Record<string, any>;
    color: string;
    icon: string;
    timestamp: Date;
    isMilestone?: boolean;
}

// ─── Color Map ──────────────────────────────────────────
const COLORS: Record<string, string> = {
    stage_change: "#3b82f6",
    interview: "#f59e0b",
    feedback: "#8b5cf6",
    note: "#eab308",
    message: "#a855f7",
    activity: "#64748b",
    offer: "#10b981",
    comment: "#06b6d4",
    tag: "#f97316",
    score: "#6366f1",
};

const ICON_MAP: Record<string, string> = {
    stage_change: "ArrowRight",
    interview: "Calendar",
    feedback: "Star",
    note: "StickyNote",
    message: "Mail",
    activity: "Activity",
    offer: "Gift",
    comment: "MessageSquare",
    tag: "Tag",
    score: "BarChart3",
};

// ─── Get Application Timeline ───────────────────────────
export async function getApplicationTimeline(applicationId: string): Promise<{ success: boolean; events?: TimelineEvent[]; error?: string }> {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return { success: false, error: "Unauthorized" };

    // Fetch all event sources in parallel
    const [
        stageHistory,
        interviews,
        notes,
        messages,
        activities,
        offer,
        comments,
        tags,
        score,
    ] = await Promise.all([
        prisma.candidateStageHistory.findMany({
            where: { application_id: applicationId },
            include: {
                stage: { select: { name: true, color: true } },
                actor: { select: { id: true, name: true, avatar_url: true } },
            },
            orderBy: { entered_at: "desc" },
        }),
        prisma.interview.findMany({
            where: { application_id: applicationId },
            include: {
                feedbacks: { include: { interviewer: { select: { id: true, name: true, avatar_url: true } } } },
                participants: { include: { user: { select: { id: true, name: true, avatar_url: true } } } },
            },
            orderBy: { scheduled_start_datetime: "desc" },
        }),
        prisma.candidateNote.findMany({
            where: { application_id: applicationId },
            include: { author: { select: { id: true, name: true, avatar_url: true } } },
            orderBy: { created_at: "desc" },
        }),
        prisma.message.findMany({
            where: {
                conversation: { application_id: applicationId },
                is_deleted: false,
            },
            include: { sender: { select: { id: true, name: true, avatar_url: true } } },
            orderBy: { created_at: "desc" },
            take: 50,
        }),
        prisma.applicationActivity.findMany({
            where: { application_id: applicationId },
            include: { actor: { select: { id: true, name: true, avatar_url: true } } },
            orderBy: { created_at: "desc" },
            take: 100,
        }),
        prisma.applicationOffer.findFirst({ where: { application_id: applicationId } }),
        prisma.teamComment.findMany({
            where: { application_id: applicationId },
            include: {
                author: { select: { id: true, name: true, avatar_url: true } },
                mentions: { include: { user: { select: { id: true, name: true } } } },
            },
            orderBy: { created_at: "desc" },
            take: 50,
        }),
        prisma.applicationTag.findMany({
            where: { application_id: applicationId },
            include: { tag: true },
        }),
        prisma.candidateScore.findFirst({ where: { application_id: applicationId } }),
    ]);

    const events: TimelineEvent[] = [];

    // ── Stage Changes ───────────────────────────────────
    for (const sh of stageHistory) {
        const isMilestone = ["offer", "hired"].some((t) =>
            sh.stage.name.toLowerCase().includes(t)
        );
        events.push({
            id: `stage-${sh.id}`,
            type: "stage_change",
            title: `Moved to ${sh.stage.name}`,
            description: sh.notes || undefined,
            actor: sh.actor || undefined,
            metadata: {
                stageName: sh.stage.name,
                stageColor: sh.stage.color,
                durationDays: sh.duration_days,
                enteredAt: sh.entered_at,
                leftAt: sh.left_at,
            },
            color: sh.stage.color || COLORS.stage_change,
            icon: ICON_MAP.stage_change,
            timestamp: sh.entered_at,
            isMilestone,
        });
    }

    // ── Interviews ──────────────────────────────────────
    for (const iv of interviews) {
        const durationMin = Math.round((iv.scheduled_end_datetime.getTime() - iv.scheduled_start_datetime.getTime()) / 60000);
        const interviewer = iv.participants.find(p => p.role === "interviewer");
        const interviewerName = interviewer?.user?.name;

        events.push({
            id: `interview-${iv.id}`,
            type: "interview",
            title: `${iv.title || iv.type} Interview`,
            description: `${durationMin} min · ${iv.type}${interviewerName ? ` with ${interviewerName}` : ""}`,
            metadata: {
                status: iv.status,
                scheduledAt: iv.scheduled_start_datetime,
                meetingLink: iv.video_conference_link,
                type: iv.type,
                feedbackCount: iv.feedbacks.length,
            },
            color: COLORS.interview,
            icon: ICON_MAP.interview,
            timestamp: iv.scheduled_start_datetime,
            isMilestone: iv.type === "final",
        });

        // ── Individual Feedback (nested under interviews) ──
        for (const sc of iv.feedbacks) {
            events.push({
                id: `feedback-${sc.id}`,
                type: "feedback",
                title: `Feedback submitted`,
                description: `Overall: ${sc.overall_rating || "N/A"}/5`,
                actor: sc.interviewer,
                metadata: {
                    technical: sc.technical_skills_rating,
                    cultureFit: sc.cultural_fit_rating,
                    overall: sc.overall_rating,
                    comments: sc.comments,
                },
                color: COLORS.feedback,
                icon: ICON_MAP.feedback,
                timestamp: sc.submitted_at,
            });
        }
    }

    // ── Notes ───────────────────────────────────────────
    for (const note of notes) {
        events.push({
            id: `note-${note.id}`,
            type: "note",
            title: "Note added",
            description: note.content.length > 200 ? note.content.substring(0, 200) + "..." : note.content,
            actor: note.author,
            metadata: { isPrivate: (note as any).is_private, fullContent: note.content },
            color: COLORS.note,
            icon: ICON_MAP.note,
            timestamp: note.created_at,
        });
    }

    // ── Messages ────────────────────────────────────────
    for (const msg of messages) {
        events.push({
            id: `message-${msg.id}`,
            type: "message",
            title: msg.message_type === "system" ? "System message" : "Message sent",
            description: msg.content.length > 150 ? msg.content.substring(0, 150) + "..." : msg.content,
            actor: msg.sender,
            metadata: { type: msg.message_type },
            color: COLORS.message,
            icon: ICON_MAP.message,
            timestamp: msg.created_at,
        });
    }

    // ── Activities (general) ────────────────────────────
    // Skip activities that are already covered by specific events
    const skipActions = new Set(["team_comment", "stage_move", "interview_scheduled"]);
    for (const act of activities) {
        if (skipActions.has(act.action)) continue;
        events.push({
            id: `activity-${act.id}`,
            type: "activity",
            title: formatActionTitle(act.action),
            description: act.details ? JSON.stringify(act.details).substring(0, 150) : undefined,
            actor: act.actor || undefined,
            metadata: act.details as any,
            color: COLORS.activity,
            icon: ICON_MAP.activity,
            timestamp: act.created_at,
        });
    }

    // ── Offer ───────────────────────────────────────────
    if (offer) {
        events.push({
            id: `offer-${offer.id}`,
            type: "offer",
            title: `Offer ${offer.status}`,
            description: offer.base_salary
                ? `${offer.currency} ${offer.base_salary.toLocaleString()}`
                : "Offer details pending",
            metadata: {
                salary: offer.base_salary,
                currency: offer.currency,
                status: offer.status,
                deadline: offer.response_deadline,
            },
            color: offer.status === "accepted" ? "#10b981" : offer.status === "declined" ? "#ef4444" : COLORS.offer,
            icon: ICON_MAP.offer,
            timestamp: offer.created_at,
            isMilestone: true,
        });
    }

    // ── Team Comments ───────────────────────────────────
    for (const c of comments) {
        const mentionNames = c.mentions.map((m: any) => m.user.name).join(", ");
        events.push({
            id: `comment-${c.id}`,
            type: "comment",
            title: "Team discussion",
            description: c.content.length > 200 ? c.content.substring(0, 200) + "..." : c.content,
            actor: c.author,
            metadata: { mentions: mentionNames, parentId: c.parent_id, fullContent: c.content },
            color: COLORS.comment,
            icon: ICON_MAP.comment,
            timestamp: c.created_at,
        });
    }

    // ── Score ────────────────────────────────────────────
    if (score) {
        events.push({
            id: `score-${score.id}`,
            type: "score",
            title: `Match score: ${Math.round(score.overall_score)}%`,
            description: score.justification || undefined,
            metadata: {
                overall: score.overall_score,
                technical: score.technical_fit,
                experience: score.experience_fit,
                education: score.education_fit,
                isAI: score.is_ai_generated,
            },
            color: COLORS.score,
            icon: ICON_MAP.score,
            timestamp: score.created_at,
            isMilestone: score.overall_score >= 80,
        });
    }

    // Sort all events by timestamp (most recent first)
    events.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

    return { success: true, events };
}

// ─── Helpers ────────────────────────────────────────────
function formatActionTitle(action: string): string {
    const map: Record<string, string> = {
        applied: "Application submitted",
        viewed: "Application viewed",
        status_changed: "Status updated",
        bulk_rejected: "Bulk rejected",
        resume_downloaded: "Resume downloaded",
        rating_updated: "Rating updated",
        tag_added: "Tag applied",
        tag_removed: "Tag removed",
        email_sent: "Email sent",
        note_added: "Note added",
    };
    return map[action] || action.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
