"use client";

import { Clock, Eye, Star, MessageSquare, ArrowRight, UserCheck, XCircle, CheckCircle, FileText } from "lucide-react";

interface ActivityLogTabProps {
    activities: any[];
    application: any;
}

const actionConfig: Record<string, { icon: any; color: string; bgColor: string }> = {
    application_submitted: { icon: FileText, color: "text-blue-600", bgColor: "bg-blue-100" },
    application_viewed: { icon: Eye, color: "text-violet-600", bgColor: "bg-violet-100" },
    status_updated: { icon: ArrowRight, color: "text-amber-600", bgColor: "bg-amber-100" },
    rating_updated: { icon: Star, color: "text-yellow-600", bgColor: "bg-yellow-100" },
    message_sent: { icon: MessageSquare, color: "text-primary", bgColor: "bg-blue-100" },
    interview_scheduled: { icon: Clock, color: "text-purple-600", bgColor: "bg-purple-100" },
    interview_completed: { icon: CheckCircle, color: "text-emerald-600", bgColor: "bg-emerald-100" },
    offer_extended: { icon: UserCheck, color: "text-green-600", bgColor: "bg-green-100" },
    application_rejected: { icon: XCircle, color: "text-red-600", bgColor: "bg-red-100" },
    shortlisted: { icon: Star, color: "text-amber-600", bgColor: "bg-amber-100" },
};

function getActionConfig(action: string) {
    return actionConfig[action] || { icon: Clock, color: "text-slate-500", bgColor: "bg-slate-100" };
}

function formatActionLabel(action: string): string {
    return action
        .replace(/_/g, " ")
        .replace(/\b\w/g, (l) => l.toUpperCase());
}

export function ActivityLogTab({ activities, application }: ActivityLogTabProps) {
    // Build a synthetic timeline including the initial application
    const timeline = [
        ...activities.map((act: any) => ({
            id: act.id,
            action: act.action,
            details: act.details,
            actor: act.actor,
            createdAt: act.created_at,
        })),
    ];

    // Add synthetic "application submitted" event if not already present
    const hasSubmitted = timeline.some((t) => t.action === "application_submitted");
    if (!hasSubmitted) {
        timeline.push({
            id: "synthetic-submitted",
            action: "application_submitted",
            details: { method: application.source || "platform" },
            actor: null,
            createdAt: application.applied_at,
        });
    }

    // Sort by date, most recent first
    timeline.sort(
        (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );

    return (
        <div className="max-w-3xl">
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-bold text-slate-900">Activity Timeline</h3>
                <span className="text-xs font-semibold text-slate-400 bg-slate-100 px-3 py-1 rounded-full">
                    {timeline.length} events
                </span>
            </div>

            {timeline.length === 0 ? (
                <div className="text-center py-12 bg-slate-50 border border-slate-100 rounded-xl text-slate-500">
                    <Clock className="w-12 h-12 mx-auto mb-3 opacity-20" />
                    <p>No activities recorded yet.</p>
                </div>
            ) : (
                <div className="relative">
                    {/* Vertical line */}
                    <div className="absolute left-5 top-0 bottom-0 w-px bg-gradient-to-b from-primary/30 via-slate-200 to-transparent" />

                    <div className="space-y-1">
                        {timeline.map((event, idx) => {
                            const config = getActionConfig(event.action);
                            const Icon = config.icon;
                            const isFirst = idx === 0;

                            return (
                                <div key={event.id} className="relative flex gap-4 py-3">
                                    {/* Icon */}
                                    <div
                                        className={`relative z-10 flex-shrink-0 w-10 h-10 rounded-xl ${config.bgColor} flex items-center justify-center ${isFirst ? "ring-2 ring-primary/20 shadow-sm" : ""
                                            }`}
                                    >
                                        <Icon className={`w-4 h-4 ${config.color}`} />
                                    </div>

                                    {/* Content */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-start justify-between gap-2">
                                            <div>
                                                <p className="text-sm font-bold text-slate-900">
                                                    {formatActionLabel(event.action)}
                                                </p>
                                                <p className="text-xs text-slate-500 mt-0.5">
                                                    {event.details?.note ||
                                                        event.details?.reason ||
                                                        event.details?.method ||
                                                        event.details?.new_status
                                                        ? `Status → ${event.details.new_status}`
                                                        : event.details?.rating
                                                            ? `Rated ${event.details.rating}/5 stars`
                                                            : ""}
                                                    {event.actor?.name && (
                                                        <span> by <strong>{event.actor.name}</strong></span>
                                                    )}
                                                    {!event.actor && event.action === "application_submitted" && (
                                                        <span> by <strong>Candidate</strong></span>
                                                    )}
                                                </p>
                                            </div>
                                            <time className="text-xs font-medium text-slate-400 whitespace-nowrap">
                                                {new Date(event.createdAt).toLocaleDateString("en-US", {
                                                    month: "short",
                                                    day: "numeric",
                                                })}{" "}
                                                {new Date(event.createdAt).toLocaleTimeString("en-US", {
                                                    hour: "2-digit",
                                                    minute: "2-digit",
                                                })}
                                            </time>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
}
