"use server";

import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import { EmailQueueService } from "@/services/EmailQueueService";
import { generateIcs } from "@/lib/email/icsGenerator";
import { format } from "date-fns";

// ─── Interview Type Config ───
export type InterviewType = "phone_screen" | "video" | "in_person" | "technical" | "panel" | "final";

const INTERVIEW_TYPE_DEFAULTS: Record<InterviewType, { duration: number; format: string }> = {
    phone_screen: { duration: 30, format: "phone" },
    video: { duration: 60, format: "video" },
    in_person: { duration: 60, format: "in_person" },
    technical: { duration: 90, format: "video" },
    panel: { duration: 75, format: "video" },
    final: { duration: 45, format: "video" },
};

// ─── Schedule Interview (Enhanced) ───
export async function scheduleInterview(
    applicationId: string,
    data: {
        title?: string;
        interview_type?: InterviewType;
        scheduled_start_datetime: string;
        duration_minutes?: number;
        format?: string;
        meeting_link?: string;
        location?: string;
        timezone?: string;
        round?: string;
        interviewer_name?: string;
        interviewer_instructions?: string;
        preparation_notes?: string;
        notes?: string;
    }
) {
    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: { select: { employer_id: true, title: true, company: true } },
            candidate: { select: { email: true, name: true } }
        },
    });

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

    const interviewType = (data.interview_type || "video") as InterviewType;
    const defaults = INTERVIEW_TYPE_DEFAULTS[interviewType] || INTERVIEW_TYPE_DEFAULTS.video;

    try {
        const interview = await prisma.interview.create({
            data: {
                application_id: applicationId,
                title: data.title || `${interviewType.replace(/_/g, " ").replace(/\b\w/g, l => l.toUpperCase())} — ${application.job.title}`,
                interview_type: interviewType,
                scheduled_start_datetime: new Date(data.scheduled_start_datetime),
                duration_minutes: data.duration_minutes || defaults.duration,
                format: data.format || defaults.format,
                meeting_link: data.meeting_link || undefined,
                location: data.location || undefined,
                timezone: data.timezone || "Africa/Lagos",
                round: data.round || undefined,
                interviewer_name: data.interviewer_name || user.name,
                interviewer_instructions: data.interviewer_instructions || undefined,
                preparation_notes: data.preparation_notes || undefined,
                notes: data.notes || undefined,
                status: "scheduled",
            },
        });

        // Update application status if in earlier stage
        if (["pending", "reviewing"].includes(application.status)) {
            await prisma.application.update({
                where: { id: applicationId },
                data: { status: "interview" },
            });
        }

        await prisma.applicationActivity.create({
            data: {
                application_id: applicationId,
                actor_id: user.id,
                action: "interview_scheduled",
                details: {
                    interview_type: interviewType,
                    title: interview.title,
                    scheduled_start_datetime: data.scheduled_start_datetime,
                    round: data.round,
                    interviewer: data.interviewer_name || user.name,
                },
            },
        });

        // --- EMAIL NOTIFICATION: Interview Invitation (with ICS) ---
        try {
            const scheduledAt = new Date(data.scheduled_start_datetime);
            const tzLabel = data.timezone || "Africa/Lagos";
            const formattedDate = format(scheduledAt, "EEEE, MMM d 'at' h:mm a") + ` (${tzLabel})`;
            const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

            let attachments = [];
            const icsContent = await generateIcs({
                title: `Interview: ${application.job.title} at ${application.job.company}`,
                description: `Scheduled interview for the ${application.job.title} position.\nType: ${interviewType}\nLink: ${data.meeting_link || 'TBD'}`,
                start: scheduledAt,
                duration: {
                    hours: Math.floor((data.duration_minutes || defaults.duration) / 60),
                    minutes: (data.duration_minutes || defaults.duration) % 60
                },
                location: data.location || data.meeting_link || 'Online',
                organizer: { name: user.name || 'Employer', email: user.email || 'noreply@protenintl.com' }
            });

            attachments.push({
                filename: 'interview-invite.ics',
                content: icsContent,
                contentType: 'text/calendar; charset=utf-8; method=REQUEST'
            });

            await EmailQueueService.enqueueEmail(
                'interview_reminder', // Using 'interview_reminder' as a general template for now or could use a specific 'interview_invitation' if needed, but the reminder template is flexible.
                application.candidate.email,
                {
                    candidateName: application.candidate.name || 'Candidate',
                    jobTitle: application.job.title,
                    companyName: application.job.company || 'Company',
                    scheduledAt: formattedDate,
                    interviewType: interviewType,
                    meetingLink: data.meeting_link,
                    location: data.location,
                    dashboardUrl: `${baseUrl}/dashboard/candidate/applications/${applicationId}`,
                    reminderType: 'invitation', // Custom reminderType for the template to distinguish
                    attachments
                },
                application.candidate_id
            );
        } catch (emailErr) {
            console.error("Failed to enqueue interview invitation email:", emailErr);
        }

        revalidatePath(`/dashboard/applications/${applicationId}`);
        revalidatePath("/dashboard/applications");
        return { success: true, interviewId: interview.id };
    } catch (error) {
        console.error("Failed to schedule interview:", error);
        return { success: false, error: "Failed to schedule interview." };
    }
}

// ─── Update Interview ───
export async function updateInterview(
    interviewId: string,
    data: {
        title?: string;
        scheduled_start_datetime?: string;
        duration_minutes?: number;
        format?: string;
        meeting_link?: string;
        location?: string;
        timezone?: string;
        round?: string;
        interviewer_name?: string;
        interviewer_instructions?: string;
        preparation_notes?: string;
        notes?: string;
    }
) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: {
                    include: { job: { select: { employer_id: true } } },
                },
            },
        });

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

        await prisma.interview.update({
            where: { id: interviewId },
            data: {
                ...(data.title && { title: data.title }),
                ...(data.scheduled_start_datetime && { scheduled_start_datetime: new Date(data.scheduled_start_datetime) }),
                ...(data.duration_minutes && { duration_minutes: data.duration_minutes }),
                ...(data.format && { format: data.format }),
                ...(data.meeting_link !== undefined && { meeting_link: data.meeting_link }),
                ...(data.location !== undefined && { location: data.location }),
                ...(data.timezone && { timezone: data.timezone }),
                ...(data.round && { round: data.round }),
                ...(data.interviewer_name && { interviewer_name: data.interviewer_name }),
                ...(data.interviewer_instructions !== undefined && { interviewer_instructions: data.interviewer_instructions }),
                ...(data.preparation_notes !== undefined && { preparation_notes: data.preparation_notes }),
                ...(data.notes !== undefined && { notes: data.notes }),
            },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: "interview_updated",
                details: { interviewId, changes: data },
            },
        });

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true };
    } catch (error) {
        console.error("Failed to update interview:", error);
        return { success: false, error: "Failed to update interview." };
    }
}

// ─── Reschedule Interview ───
export async function rescheduleInterview(
    interviewId: string,
    newDateTime: string,
    reason?: string
) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: {
                    include: {
                        job: { select: { employer_id: true, title: true, company: true, employer: { select: { email: true, name: true } } } },
                        candidate: { select: { email: true, name: true, id: true } }
                    },
                },
            },
        });
        if (!interview) return { success: false, error: "Interview not found" };

        // Both employer and candidate can request reschedule
        const isEmployer = user.role === "employer" && interview.application.job.employer_id === user.id;
        const isCandidate = user.role === "candidate" && interview.application.candidate_id === user.id;

        if (!isEmployer && !isCandidate) {
            return { success: false, error: "Unauthorized" };
        }

        const oldDate = interview.scheduled_start_datetime.toISOString();

        if (isEmployer) {
            // Employer directly reschedules
            await prisma.interview.update({
                where: { id: interviewId },
                data: {
                    scheduled_start_datetime: new Date(newDateTime),
                    reschedule_reason: reason || undefined,
                    candidate_confirmed: false,
                    candidate_response: null,
                },
            });
        } else {
            // Candidate requests reschedule
            await prisma.interview.update({
                where: { id: interviewId },
                data: {
                    candidate_response: "reschedule_requested",
                    reschedule_reason: reason || undefined,
                },
            });
        }

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: isEmployer ? "interview_rescheduled" : "interview_reschedule_requested",
                details: {
                    interviewId,
                    old_date: oldDate,
                    new_date: newDateTime,
                    reason,
                    initiated_by: user.role,
                },
            },
        });

        // Send notification email to the other party
        const oldDateStr = new Date(oldDate).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        const newDateStr = new Date(newDateTime).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        const jobTitle = interview.application.job.title;
        const company = interview.application.job.company;

        // --- EMAIL NOTIFICATION: Reschedule ---
        try {
            const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
            if (isEmployer) {
                const scheduledAt = new Date(newDateTime);
                const tzLabel = interview.timezone || "Africa/Lagos";
                const formattedDate = format(scheduledAt, "EEEE, MMM d 'at' h:mm a") + ` (${tzLabel})`;

                let attachments = [];
                const icsContent = await generateIcs({
                    title: `RESCHEDULED: Interview for ${jobTitle}`,
                    description: `The interview has been rescheduled.\nReason: ${reason || 'Not provided'}`,
                    start: scheduledAt,
                    duration: { hours: 1, minutes: 0 },
                    location: interview.location || interview.meeting_link || 'Online',
                    organizer: { name: user.name || 'Employer', email: user.email || 'noreply@protenintl.com' },
                    sequence: (interview.ics_sequence || 0) + 1
                });

                attachments.push({
                    filename: 'interview-reschedule.ics',
                    content: icsContent,
                    contentType: 'text/calendar; charset=utf-8; method=REQUEST'
                });

                await EmailQueueService.enqueueEmail(
                    'interview_reminder',
                    interview.application.candidate.email,
                    {
                        candidateName: interview.application.candidate.name || 'Candidate',
                        jobTitle,
                        companyName: company || 'Company',
                        scheduledAt: formattedDate,
                        interviewType: interview.interview_type,
                        meetingLink: interview.meeting_link,
                        location: interview.location,
                        dashboardUrl: `${baseUrl}/dashboard/candidate/applications/${interview.application_id}`,
                        reminderType: 'rescheduled',
                        rescheduleReason: reason,
                        attachments
                    },
                    interview.application.candidate_id
                );

                // Increment sequence
                await prisma.interview.update({
                    where: { id: interviewId },
                    data: { ics_sequence: { increment: 1 } }
                });
            } else {
                // Notify Employer of candidate's request
                await EmailQueueService.enqueueEmail(
                    'notification', // Use general notification for employer requester
                    interview.application.job.employer.email,
                    {
                        title: `Reschedule Request: ${interview.application.candidate.name}`,
                        message: `The candidate has requested to reschedule the interview for ${jobTitle}.\nRequested New Date: ${new Date(newDateTime).toLocaleString()}\n${reason ? `Reason: ${reason}` : ''}`,
                        actionUrl: `${baseUrl}/dashboard/employer/jobs/${interview.application.job_id}/applications/${interview.application_id}`
                    },
                    interview.application.job.employer_id
                );
            }
        } catch (emailErr) {
            console.error("Failed to enqueue reschedule email:", emailErr);
        }

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true };
    } catch (error) {
        console.error("Failed to reschedule:", error);
        return { success: false, error: "Failed to reschedule interview." };
    }
}

// ─── Confirm Interview (Candidate) ───
export async function confirmInterview(interviewId: string) {
    const user = await getCurrentUser();
    if (!user || user.role !== "candidate") {
        return { success: false, error: "Unauthorized" };
    }

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: { select: { candidate_id: true, id: true } },
            },
        });
        if (!interview || interview.application.candidate_id !== user.id) {
            return { success: false, error: "Interview not found" };
        }

        await prisma.interview.update({
            where: { id: interviewId },
            data: {
                candidate_confirmed: true,
                candidate_response: "confirmed",
            },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: "interview_confirmed",
                details: { interviewId, confirmed_by: "candidate" },
            },
        });

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true };
    } catch (error) {
        console.error("Failed to confirm interview:", error);
        return { success: false, error: "Failed to confirm interview." };
    }
}

// ─── Cancel Interview ───
export async function cancelInterview(interviewId: string) {
    const user = await getCurrentUser();
    if (!user) return { success: false, error: "Unauthorized" };

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: {
                    include: {
                        job: { select: { employer_id: true, title: true, company: true, employer: { select: { email: true, name: true } } } },
                        candidate: { select: { email: true, name: true, id: true } }
                    },
                },
            },
        });
        if (!interview) return { success: false, error: "Interview not found" };

        const isEmployer = user.role === "employer" && interview.application.job.employer_id === user.id;
        const isCandidate = user.role === "candidate" && interview.application.candidate_id === user.id;

        if (!isEmployer && !isCandidate) {
            return { success: false, error: "Unauthorized" };
        }

        await prisma.interview.update({
            where: { id: interviewId },
            data: {
                status: "cancelled",
                ...(isCandidate && { candidate_response: "declined" }),
            },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: "interview_cancelled",
                details: {
                    interviewId,
                    cancelled_by: user.role,
                    was_scheduled_start_datetime: interview.scheduled_start_datetime.toISOString(),
                },
            },
        });

        const cancelDateStr = new Date(interview.scheduled_start_datetime).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        const jobTitle = interview.application.job.title;
        const company = interview.application.job.company;

        // --- EMAIL NOTIFICATION: Cancellation ---
        try {
            const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
            const scheduledAt = new Date(interview.scheduled_start_datetime);
            const formattedDate = format(scheduledAt, "EEEE, MMM d 'at' h:mm a");

            if (isEmployer) {
                await EmailQueueService.enqueueEmail(
                    'interview_reminder',
                    interview.application.candidate.email,
                    {
                        candidateName: interview.application.candidate.name || 'Candidate',
                        jobTitle,
                        companyName: company || 'Company',
                        scheduledAt: formattedDate,
                        dashboardUrl: `${baseUrl}/dashboard/candidate/applications/${interview.application_id}`,
                        reminderType: 'cancelled'
                    },
                    interview.application.candidate_id
                );
            } else {
                // Notify Employer
                await EmailQueueService.enqueueEmail(
                    'notification',
                    interview.application.job.employer.email,
                    {
                        title: `Interview Cancelled: ${interview.application.candidate.name}`,
                        message: `The candidate has cancelled their interview for ${jobTitle} scheduled for ${formattedDate}.`,
                        actionUrl: `${baseUrl}/dashboard/employer/jobs/${interview.application.job_id}/applications/${interview.application_id}`
                    },
                    interview.application.job.employer_id
                );
            }
        } catch (emailErr) {
            console.error("Failed to enqueue cancellation email:", emailErr);
        }

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true };
    } catch (error) {
        console.error("Failed to cancel interview:", error);
        return { success: false, error: "Failed to cancel interview." };
    }
}

// ─── Complete Interview ───
export async function completeInterview(
    interviewId: string,
    feedback?: string
) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: {
                    include: { job: { select: { employer_id: true } } },
                },
            },
        });

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

        await prisma.interview.update({
            where: { id: interviewId },
            data: {
                status: "completed",
                notes: feedback
                    ? interview.notes
                        ? `${interview.notes}\n\n--- Feedback ---\n${feedback}`
                        : feedback
                    : interview.notes,
            },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: "interview_completed",
                details: {
                    interviewId,
                    had_feedback: !!feedback,
                },
            },
        });

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true };
    } catch (error) {
        console.error("Failed to complete interview:", error);
        return { success: false, error: "Failed to complete interview." };
    }
}

// ─── Submit Scorecard ───
export async function submitScorecard(
    interviewId: string,
    data: {
        technical_score?: number;
        communication_score?: number;
        problem_solving_score?: number;
        culture_fit_score?: number;
        overall_score?: number;
        recommendation?: string;
        strengths?: string;
        concerns?: string;
        additional_notes?: string;
    }
) {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return { success: false, error: "Unauthorized" };
    }

    try {
        const interview = await prisma.interview.findUnique({
            where: { id: interviewId },
            include: {
                application: {
                    include: { job: { select: { employer_id: true } } },
                },
            },
        });

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

        const scorecard = await prisma.interviewScorecard.upsert({
            where: {
                interview_id_interviewer_id: {
                    interview_id: interviewId,
                    interviewer_id: user.id,
                },
            },
            update: {
                ...data,
            },
            create: {
                interview_id: interviewId,
                interviewer_id: user.id,
                ...data,
            },
        });

        await prisma.applicationActivity.create({
            data: {
                application_id: interview.application_id,
                actor_id: user.id,
                action: "scorecard_submitted",
                details: {
                    interviewId,
                    overall_score: data.overall_score,
                    recommendation: data.recommendation,
                },
            },
        });

        revalidatePath(`/dashboard/applications/${interview.application_id}`);
        return { success: true, scorecardId: scorecard.id };
    } catch (error) {
        console.error("Failed to submit scorecard:", error);
        return { success: false, error: "Failed to submit scorecard." };
    }
}

// ─── Get Interview Analytics ───
export async function getInterviewAnalytics() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") {
        return null;
    }

    try {
        // Total interviews by this employer's jobs
        const interviews = await prisma.interview.findMany({
            where: {
                application: {
                    job: { employer_id: user.id },
                },
            },
            include: {
                scorecards: true,
            },
        });

        const total = interviews.length;
        const byType: Record<string, number> = {};
        const byStatus: Record<string, number> = {};
        let totalDuration = 0;
        let confirmedCount = 0;
        let scorecardCount = 0;
        let totalOverallScore = 0;
        let scoredCount = 0;

        for (const iv of interviews) {
            byType[iv.interview_type] = (byType[iv.interview_type] || 0) + 1;
            byStatus[iv.status] = (byStatus[iv.status] || 0) + 1;
            totalDuration += iv.duration_minutes;
            if (iv.candidate_confirmed) confirmedCount++;
            for (const sc of iv.scorecards) {
                scorecardCount++;
                if (sc.overall_score) {
                    totalOverallScore += sc.overall_score;
                    scoredCount++;
                }
            }
        }

        const scheduled = byStatus["scheduled"] || 0;
        const completed = byStatus["completed"] || 0;
        const cancelled = byStatus["cancelled"] || 0;
        const noShowRate = total > 0 ? Math.round((cancelled / total) * 100) : 0;
        const confirmationRate = total > 0 ? Math.round((confirmedCount / total) * 100) : 0;
        const avgScore = scoredCount > 0 ? +(totalOverallScore / scoredCount).toFixed(1) : null;

        return {
            total,
            scheduled,
            completed,
            cancelled,
            byType,
            noShowRate,
            confirmationRate,
            avgDurationMinutes: total > 0 ? Math.round(totalDuration / total) : 0,
            avgScore,
            scorecardCount,
        };
    } catch (error) {
        console.error("Failed to get interview analytics:", error);
        return null;
    }
}

// ─── Get Employer Interviews (For Calendar View) ───
export async function getEmployerInterviews() {
    const user = await getCurrentUser();
    if (!user || user.role !== "employer") return [];

    try {
        const interviews = await prisma.interview.findMany({
            where: {
                application: {
                    job: {
                        employer_id: user.id
                    }
                }
            },
            include: {
                application: {
                    select: {
                        candidate: { select: { name: true, email: true } },
                        job: { select: { title: true } }
                    }
                }
            },
            orderBy: {
                scheduled_start_datetime: "asc"
            }
        });

        return interviews;
    } catch (error) {
        console.error("Failed to fetch employer interviews:", error);
        return [];
    }
}
