"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
    Video, Phone, MapPin, Code2, Users, Award, Clock, Calendar,
    CheckCircle2, Globe, Link2, FileText, User, AlertCircle,
    ChevronDown, ChevronUp, Download, RefreshCw, XCircle, Loader2
} from "lucide-react";
import { confirmInterview, rescheduleInterview, cancelInterview } from "@/app/actions/interviewActions";

// ─── Type configs ───
const typeConfig: Record<string, { icon: any; label: string; color: string; bgColor: string }> = {
    phone_screen: { icon: Phone, label: "Phone Screen", color: "text-emerald-600", bgColor: "bg-emerald-100" },
    video: { icon: Video, label: "Video Interview", color: "text-blue-600", bgColor: "bg-blue-100" },
    in_person: { icon: MapPin, label: "In-Person Interview", color: "text-violet-600", bgColor: "bg-violet-100" },
    technical: { icon: Code2, label: "Technical Assessment", color: "text-orange-600", bgColor: "bg-orange-100" },
    panel: { icon: Users, label: "Panel Interview", color: "text-pink-600", bgColor: "bg-pink-100" },
    final: { icon: Award, label: "Final Interview", color: "text-amber-600", bgColor: "bg-amber-100" },
};

const roundLabels: Record<string, string> = {
    initial_screen: "Initial Screen",
    first_round: "1st Round",
    second_round: "2nd Round",
    technical: "Technical Assessment",
    final: "Final Round",
};

interface CandidateInterviewViewProps {
    interviews: any[];
    applicationId: string;
}

export function CandidateInterviewView({ interviews, applicationId }: CandidateInterviewViewProps) {
    const scheduled = interviews.filter(
        (i) => i.status === "scheduled" && new Date(i.scheduled_at) >= new Date()
    );
    const past = interviews.filter(
        (i) => i.status !== "scheduled" || new Date(i.scheduled_at) < new Date()
    );

    if (interviews.length === 0) {
        return (
            <div className="text-center py-16 bg-slate-50/50 border-2 border-dashed border-slate-200 rounded-2xl">
                <Calendar className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                <h4 className="text-lg font-bold text-slate-700">No Interviews Scheduled</h4>
                <p className="text-sm text-slate-500 mt-1 max-w-sm mx-auto">
                    No interviews have been scheduled yet. The employer will reach out when ready.
                </p>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {scheduled.length > 0 && (
                <div>
                    <h4 className="text-sm font-bold text-slate-500 uppercase tracking-wide mb-3">
                        Upcoming Interviews
                    </h4>
                    <div className="space-y-4">
                        {scheduled.map((interview) => (
                            <InterviewDetailCard key={interview.id} interview={interview} />
                        ))}
                    </div>
                </div>
            )}

            {past.length > 0 && (
                <div>
                    <h4 className="text-sm font-bold text-slate-500 uppercase tracking-wide mb-3">
                        Past Interviews
                    </h4>
                    <div className="space-y-3">
                        {past.map((interview) => (
                            <PastInterviewCard key={interview.id} interview={interview} />
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

// ─── Upcoming Interview Detail Card ───
function InterviewDetailCard({ interview }: { interview: any }) {
    const router = useRouter();
    const [showReschedule, setShowReschedule] = useState(false);
    const [rescheduleDate, setRescheduleDate] = useState("");
    const [rescheduleReason, setRescheduleReason] = useState("");
    const [actionLoading, setActionLoading] = useState<string | null>(null);

    const tc = typeConfig[interview.interview_type] || typeConfig.video;
    const TypeIcon = tc.icon;
    const date = new Date(interview.scheduled_at);
    const endDate = new Date(date.getTime() + interview.duration_minutes * 60000);
    const isConfirmed = interview.candidate_confirmed;

    // Countdown
    const diff = date.getTime() - Date.now();
    const days = Math.floor(diff / 86400000);
    const hours = Math.floor((diff % 86400000) / 3600000);
    const mins = Math.floor((diff % 3600000) / 60000);

    const handleConfirm = async () => {
        setActionLoading("confirm");
        try {
            await confirmInterview(interview.id);
            router.refresh();
        } finally {
            setActionLoading(null);
        }
    };

    const handleReschedule = async () => {
        if (!rescheduleDate) return;
        setActionLoading("reschedule");
        try {
            await rescheduleInterview(interview.id, rescheduleDate, rescheduleReason);
            setShowReschedule(false);
            router.refresh();
        } finally {
            setActionLoading(null);
        }
    };

    const handleCancel = async () => {
        if (!window.confirm("Are you sure you want to cancel this interview?")) return;
        setActionLoading("cancel");
        try {
            await cancelInterview(interview.id);
            router.refresh();
        } finally {
            setActionLoading(null);
        }
    };

    // Generate .ics content and download
    const generateICS = () => {
        const pad = (n: number) => String(n).padStart(2, "0");
        const formatDate = (d: Date) =>
            `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}00Z`;

        const ics = [
            "BEGIN:VCALENDAR",
            "VERSION:2.0",
            "PRODID:-//JobBoard//Interview//EN",
            "BEGIN:VEVENT",
            `DTSTART:${formatDate(date)}`,
            `DTEND:${formatDate(endDate)}`,
            `SUMMARY:${interview.title || tc.label}`,
            `DESCRIPTION:${interview.preparation_notes || "Interview"}`,
            interview.location ? `LOCATION:${interview.location}` : "",
            interview.meeting_link ? `URL:${interview.meeting_link}` : "",
            "END:VEVENT",
            "END:VCALENDAR",
        ].filter(Boolean).join("\r\n");

        const blob = new Blob([ics], { type: "text/calendar" });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `interview-${date.toISOString().split("T")[0]}.ics`;
        link.click();
        URL.revokeObjectURL(url);
    };

    return (
        <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
            {/* Header with gradient */}
            <div className={`bg-gradient-to-r from-primary to-indigo-600 px-6 py-5`}>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-12 h-12 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center">
                            <TypeIcon className="w-6 h-6 text-white" />
                        </div>
                        <div>
                            <p className="text-white/70 text-xs font-bold uppercase tracking-widest">
                                {tc.label}
                            </p>
                            <p className="text-lg font-extrabold text-white">
                                {interview.title || tc.label}
                            </p>
                        </div>
                    </div>
                    {isConfirmed ? (
                        <span className="inline-flex items-center gap-1 px-3 py-1 bg-emerald-500/20 text-emerald-100 text-xs font-bold rounded-full">
                            <CheckCircle2 className="w-3 h-3" /> Confirmed
                        </span>
                    ) : (
                        <span className="inline-flex items-center gap-1 px-3 py-1 bg-amber-500/20 text-amber-100 text-xs font-bold rounded-full">
                            <AlertCircle className="w-3 h-3" /> Pending Confirmation
                        </span>
                    )}
                </div>
            </div>

            <div className="p-6 space-y-5">
                {/* Countdown */}
                <div className="flex items-center gap-6 p-4 bg-gradient-to-r from-primary/5 to-indigo-50 rounded-xl">
                    <div className="text-center">
                        <p className="text-3xl font-black text-primary">{days}</p>
                        <p className="text-[10px] font-bold text-primary/60 uppercase">days</p>
                    </div>
                    <div className="text-center">
                        <p className="text-3xl font-black text-primary">{hours}</p>
                        <p className="text-[10px] font-bold text-primary/60 uppercase">hours</p>
                    </div>
                    <div className="text-center">
                        <p className="text-3xl font-black text-primary">{mins}</p>
                        <p className="text-[10px] font-bold text-primary/60 uppercase">minutes</p>
                    </div>
                    <p className="text-sm text-slate-500 ml-auto">until interview</p>
                </div>

                {/* Date & Time */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="flex items-center gap-3 p-3 bg-slate-50 rounded-xl">
                        <Calendar className="w-5 h-5 text-slate-400" />
                        <div>
                            <p className="text-xs text-slate-400 font-semibold">Date</p>
                            <p className="text-sm font-bold text-slate-900">
                                {date.toLocaleDateString("en-US", {
                                    weekday: "long",
                                    month: "long",
                                    day: "numeric",
                                    year: "numeric",
                                })}
                            </p>
                        </div>
                    </div>
                    <div className="flex items-center gap-3 p-3 bg-slate-50 rounded-xl">
                        <Clock className="w-5 h-5 text-slate-400" />
                        <div>
                            <p className="text-xs text-slate-400 font-semibold">Time</p>
                            <p className="text-sm font-bold text-slate-900">
                                {date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                                {" — "}
                                {endDate.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                                <span className="text-xs text-slate-400 ml-1">
                                    ({interview.duration_minutes}min)
                                </span>
                            </p>
                        </div>
                    </div>
                </div>

                {/* Location / Meeting Link */}
                {interview.meeting_link && (
                    <div className="p-4 bg-blue-50 border border-blue-100 rounded-xl">
                        <p className="text-xs font-bold text-blue-500 uppercase tracking-wide mb-2">
                            Meeting Link
                        </p>
                        <a
                            href={interview.meeting_link}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white font-semibold text-sm rounded-lg hover:bg-blue-700 transition-colors"
                        >
                            <Link2 className="w-4 h-4" /> Join Meeting
                        </a>
                        <p className="text-xs text-blue-400 mt-2">
                            Link will be active 10 minutes before the scheduled time
                        </p>
                    </div>
                )}

                {interview.location && (
                    <div className="p-4 bg-violet-50 border border-violet-100 rounded-xl">
                        <p className="text-xs font-bold text-violet-500 uppercase tracking-wide mb-1">
                            Location
                        </p>
                        <p className="text-sm font-semibold text-violet-900 flex items-center gap-1.5">
                            <MapPin className="w-4 h-4" /> {interview.location}
                        </p>
                    </div>
                )}

                {/* Who You'll Meet */}
                {interview.interviewer_name && (
                    <div>
                        <p className="text-xs font-bold text-slate-500 uppercase tracking-wide mb-2">
                            Who You&apos;ll Meet
                        </p>
                        <div className="flex flex-wrap gap-2">
                            {interview.interviewer_name.split(",").map((name: string, i: number) => (
                                <div key={i} className="flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-xl border border-slate-100">
                                    <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                                        <User className="w-4 h-4 text-primary" />
                                    </div>
                                    <span className="text-sm font-semibold text-slate-900">{name.trim()}</span>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Round */}
                {interview.round && (
                    <div className="flex items-center gap-2 text-sm">
                        <span className="text-slate-400 font-semibold">Stage:</span>
                        <span className="px-2 py-0.5 text-xs font-bold rounded-full bg-slate-100 text-slate-700">
                            {roundLabels[interview.round] || interview.round}
                        </span>
                    </div>
                )}

                {/* Preparation Notes */}
                {interview.preparation_notes && (
                    <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-xl">
                        <p className="text-xs font-bold text-emerald-600 uppercase tracking-wide mb-2 flex items-center gap-1">
                            <FileText className="w-3.5 h-3.5" /> How to Prepare
                        </p>
                        <p className="text-sm text-emerald-900 whitespace-pre-line leading-relaxed">
                            {interview.preparation_notes}
                        </p>
                    </div>
                )}

                {/* Tips */}
                <div className="p-4 bg-amber-50 border border-amber-100 rounded-xl">
                    <p className="text-xs font-bold text-amber-600 uppercase tracking-wide mb-2">
                        💡 Quick Tips
                    </p>
                    <ul className="text-sm text-amber-800 space-y-1">
                        <li>• Review the job description and your application</li>
                        <li>• Prepare 2-3 questions to ask the interviewer(s)</li>
                        {(interview.format === "video" || interview.interview_type === "video") && (
                            <li>• Test your camera, microphone, and internet connection</li>
                        )}
                        {interview.interview_type === "technical" && (
                            <li>• Have your coding environment ready and tested</li>
                        )}
                        <li>• Join 5 minutes early to settle in</li>
                    </ul>
                </div>

                {/* Actions */}
                <div className="flex flex-wrap gap-3 pt-2">
                    {/* Confirm */}
                    {!isConfirmed && (
                        <button
                            onClick={handleConfirm}
                            disabled={actionLoading === "confirm"}
                            className="inline-flex items-center gap-2 px-5 py-2.5 bg-emerald-600 text-white font-semibold text-sm rounded-xl hover:bg-emerald-700 transition-colors disabled:opacity-50 shadow-sm"
                        >
                            {actionLoading === "confirm" ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                                <CheckCircle2 className="w-4 h-4" />
                            )}
                            Confirm Attendance
                        </button>
                    )}

                    {/* Reschedule */}
                    <button
                        onClick={() => setShowReschedule(!showReschedule)}
                        className="inline-flex items-center gap-2 px-4 py-2.5 text-amber-700 bg-amber-50 font-semibold text-sm rounded-xl hover:bg-amber-100 transition-colors border border-amber-200"
                    >
                        <RefreshCw className="w-4 h-4" />
                        Request Reschedule
                    </button>

                    {/* Add to Calendar */}
                    <button
                        onClick={generateICS}
                        className="inline-flex items-center gap-2 px-4 py-2.5 text-slate-600 bg-white font-semibold text-sm rounded-xl hover:bg-slate-50 transition-colors border border-slate-200"
                    >
                        <Download className="w-4 h-4" />
                        Add to Calendar
                    </button>

                    {/* Cancel */}
                    <button
                        onClick={handleCancel}
                        disabled={actionLoading === "cancel"}
                        className="inline-flex items-center gap-2 px-4 py-2.5 text-red-600 text-sm font-semibold hover:text-red-700 transition-colors"
                    >
                        <XCircle className="w-4 h-4" />
                        Cancel
                    </button>
                </div>

                {/* Reschedule Form */}
                {showReschedule && (
                    <div className="p-4 bg-amber-50/50 border border-amber-200 rounded-xl space-y-3 animate-[fadeIn_0.2s_ease-out]">
                        <h4 className="text-sm font-bold text-amber-800">Request Reschedule</h4>
                        <div>
                            <label className="block text-xs font-semibold text-slate-600 mb-1">
                                Preferred Date & Time
                            </label>
                            <input
                                type="datetime-local"
                                value={rescheduleDate}
                                onChange={(e) => setRescheduleDate(e.target.value)}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-amber-300 focus:border-amber-400 outline-none"
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-slate-600 mb-1">
                                Reason (optional)
                            </label>
                            <textarea
                                value={rescheduleReason}
                                onChange={(e) => setRescheduleReason(e.target.value)}
                                rows={2}
                                placeholder="Brief reason for requesting a different time..."
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-amber-300 focus:border-amber-400 outline-none resize-none"
                            />
                        </div>
                        <div className="flex justify-end gap-2">
                            <button
                                onClick={() => setShowReschedule(false)}
                                className="px-3 py-1.5 text-xs font-semibold text-slate-500"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleReschedule}
                                disabled={!rescheduleDate || actionLoading === "reschedule"}
                                className="px-4 py-1.5 bg-amber-600 text-white text-xs font-semibold rounded-lg hover:bg-amber-700 disabled:opacity-50"
                            >
                                {actionLoading === "reschedule" ? "Sending..." : "Submit Request"}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

// ─── Past Interview Card (compact) ───
function PastInterviewCard({ interview }: { interview: any }) {
    const tc = typeConfig[interview.interview_type] || typeConfig.video;
    const TypeIcon = tc.icon;
    const date = new Date(interview.scheduled_at);

    return (
        <div className="flex items-center gap-4 p-4 bg-white border border-slate-200 rounded-xl opacity-75">
            <div className={`w-10 h-10 rounded-xl ${tc.bgColor} flex items-center justify-center`}>
                <TypeIcon className={`w-5 h-5 ${tc.color}`} />
            </div>
            <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-slate-900 truncate">
                    {interview.title || tc.label}
                </p>
                <p className="text-xs text-slate-500">
                    {date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                    {" · "}
                    {date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                    {" · "}
                    {interview.duration_minutes}min
                </p>
            </div>
            <span className={`px-2 py-0.5 text-xs font-bold rounded-full ${interview.status === "completed"
                    ? "bg-emerald-100 text-emerald-700"
                    : "bg-red-100 text-red-700"
                }`}>
                {interview.status}
            </span>
        </div>
    );
}
