"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 startDatetime = new Date(data.scheduled_start_datetime);
        const duration = data.duration_minutes || defaults.duration;
        const endDatetime = new Date(startDatetime.getTime() + duration * 60000);

        const interview = await prisma.interview.create({
            data: {
                application_id: applicationId,
                job_id: application.job_id,
                created_by_user_id: user.id,
                title: data.title || `${interviewType.replace(/_/g, " ").replace(/\b\w/g, l => l.toUpperCase())} — ${application.job.title}`,
                type: data.format || defaults.format,
                scheduled_start_datetime: startDatetime,
                scheduled_end_datetime: endDatetime,
                video_conference_link: data.meeting_link || undefined,
                location: data.location || undefined,
                timezone: data.timezone || "Africa/Lagos",
                internal_notes: data.notes || undefined,
                preparation_instructions: data.preparation_notes || undefined,
                status: "scheduled",
                participants: {
                    create: [
                        { user_id: application.candidate_id, role: "candidate" },
                        { user_id: user.id, role: "interviewer", response: "accepted", confirmed_at: new Date() }
                    ]
                }
            },
        });

        // 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" };
        }

        const startDatetime = data.scheduled_start_datetime 
            ? new Date(data.scheduled_start_datetime) 
            : new Date(interview.scheduled_start_datetime);
        
        const endDatetime = new Date(startDatetime.getTime() + (data.duration_minutes || ((interview.scheduled_end_datetime.getTime() - interview.scheduled_start_datetime.getTime()) / 60000)) * 60000);

        await prisma.interview.update({
            where: { id: interviewId },
            data: {
                ...(data.title && { title: data.title }),
                ...(data.scheduled_start_datetime && { scheduled_start_datetime: startDatetime, scheduled_end_datetime: endDatetime }),
                ...(!data.scheduled_start_datetime && data.duration_minutes && { scheduled_end_datetime: endDatetime }),
                ...(data.format && { type: data.format }),
                ...(data.meeting_link !== undefined && { video_conference_link: data.meeting_link }),
                ...(data.location !== undefined && { location: data.location }),
                ...(data.timezone && { timezone: data.timezone }),
                ...(data.preparation_notes !== undefined && { preparation_instructions: data.preparation_notes }),
                ...(data.notes !== undefined && { internal_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();
        const durationMs = interview.scheduled_end_datetime.getTime() - interview.scheduled_start_datetime.getTime();

        if (isEmployer) {
            // Employer directly reschedules
            await prisma.interview.update({
                where: { id: interviewId },
                data: {
                    scheduled_start_datetime: new Date(newDateTime),
                    scheduled_end_datetime: new Date(new Date(newDateTime).getTime() + durationMs),
                    participants: {
                        updateMany: {
                            where: { role: "candidate" },
                            data: { response: "no_response", confirmed_at: null }
                        }
                    },
                    audit_logs: {
                        create: {
                            user_id: user.id,
                            action: "rescheduled",
                            old_value: { date: oldDate },
                            new_value: { date: newDateTime, reason }
                        }
                    }
                },
            });
        } else {
            // Candidate requests reschedule
            await prisma.interview.update({
                where: { id: interviewId },
                data: {
                    participants: {
                        updateMany: {
                            where: { role: "candidate", user_id: user.id },
                            data: { response: "declined" }
                        }
                    },
                    audit_logs: {
                        create: {
                            user_id: user.id,
                            action: "reschedule_requested",
                            new_value: { reason }
                        }
                    }
                },
            });
        }

        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.video_conference_link || 'Online',
                    organizer: { name: user.name || 'Employer', email: user.email || 'noreply@protenintl.com' },
                    sequence: 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.type,
                        meetingLink: interview.video_conference_link,
                        location: interview.location,
                        dashboardUrl: `${baseUrl}/dashboard/candidate/applications/${interview.application_id}`,
                        reminderType: 'rescheduled',
                        rescheduleReason: reason,
                        attachments
                    },
                    interview.application.candidate_id
                );
            } 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: {
                participants: {
                    updateMany: {
                        where: { role: 'candidate', user_id: user.id },
                        data: { confirmed_at: new Date(), response: "accepted" }
                    }
                }
            },
        });

        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, 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" };

        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",
                participants: isCandidate ? {
                    updateMany: {
                        where: { role: "candidate", user_id: user.id },
                        data: { response: "declined" }
                    }
                } : undefined,
                audit_logs: {
                    create: {
                        user_id: user.id,
                        action: "cancelled",
                        new_value: { reason: reason || "Cancelled by user" }
                    }
                }
            },
        });

        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",
                internal_notes: feedback 
                    ? interview.internal_notes 
                        ? `${interview.internal_notes}\n\n--- Feedback ---\n${feedback}` 
                        : feedback 
                    : interview.internal_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.interviewFeedback.upsert({
            where: {
                interview_id_interviewer_user_id: {
                    interview_id: interviewId,
                    interviewer_user_id: user.id,
                },
            },
            update: {
                overall_rating: data.overall_score,
                technical_skills_rating: data.technical_score,
                cultural_fit_rating: data.culture_fit_score,
                comments: data.additional_notes || data.recommendation || '',
            },
            create: {
                interview_id: interviewId,
                interviewer_user_id: user.id,
                overall_rating: data.overall_score,
                technical_skills_rating: data.technical_score,
                cultural_fit_rating: data.culture_fit_score,
                comments: data.additional_notes || data.recommendation || '',
            },
        });

        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 {
        const interviews = await prisma.interview.findMany({
            where: {
                application: {
                    job: { employer_id: user.id },
                },
            },
            include: {
                feedbacks: true,
                participants: true,
            },
        });

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

        let scorecardCount = 0;
        let totalOverallScore = 0;
        let scoredCount = 0;

        for (const iv of interviews) {
            byType[iv.type] = (byType[iv.type] || 0) + 1;
            byStatus[iv.status] = (byStatus[iv.status] || 0) + 1;

            totalDuration += (iv.scheduled_end_datetime.getTime() - iv.scheduled_start_datetime.getTime()) / 60000;

            if (iv.participants.some(p => p.role === "candidate" && p.confirmed_at)) {
                confirmedCount++;
            }

            for (const sc of iv.feedbacks) {
                scorecardCount++;
                if (sc.overall_rating) {
                    totalOverallScore += sc.overall_rating;
                    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 [];
    }
}
