"use client";

import Link from "next/link";
import { Star, Calendar, MapPin, FileText, MessageSquare, Eye, MoreHorizontal, Tag } from "lucide-react";
import { useState } from "react";
import { updateApplicationRating } from "@/app/actions/employerDashboard";
import { useRouter } from "next/navigation";

interface ApplicationCardDetailedProps {
    application: any;
    onSelect?: (id: string, selected: boolean) => void;
    isSelected?: boolean;
}

const statusConfig: Record<string, { label: string; className: string }> = {
    pending: { label: "New", className: "bg-amber-50 text-amber-700 border-amber-200" },
    reviewing: { label: "Reviewing", className: "bg-cyan-50 text-cyan-700 border-cyan-200" },
    interview: { label: "Interview", className: "bg-blue-50 text-blue-700 border-blue-200" },
    offer: { label: "Offer", className: "bg-emerald-50 text-emerald-700 border-emerald-200" },
    hired: { label: "Hired", className: "bg-green-50 text-green-800 border-green-200" },
    rejected: { label: "Rejected", className: "bg-red-50 text-red-700 border-red-200" },
    withdrawn: { label: "Withdrawn", className: "bg-slate-50 text-slate-600 border-slate-200" },
};

function getMatchColor(score: number | null | undefined) {
    if (!score) return "text-slate-400";
    if (score >= 85) return "text-emerald-600";
    if (score >= 70) return "text-blue-600";
    if (score >= 50) return "text-amber-600";
    return "text-red-500";
}

function getMatchBg(score: number | null | undefined) {
    if (!score) return "bg-slate-50";
    if (score >= 85) return "bg-emerald-50 border-emerald-200";
    if (score >= 70) return "bg-blue-50 border-blue-200";
    if (score >= 50) return "bg-amber-50 border-amber-200";
    return "bg-red-50 border-red-200";
}

function getWaitingDays(appliedAt: string | Date): { days: number; color: string } {
    const applied = new Date(appliedAt);
    const now = new Date();
    const days = Math.floor((now.getTime() - applied.getTime()) / (1000 * 60 * 60 * 24));
    let color = "text-emerald-600";
    if (days >= 8) color = "text-red-600";
    else if (days >= 4) color = "text-amber-600";
    return { days, color };
}

export function ApplicationCardDetailed({
    application,
    onSelect,
    isSelected = false,
}: ApplicationCardDetailedProps) {
    const candidate = application.candidate;
    const job = application.job;
    const profile = candidate?.profile;
    const skills = candidate?.skills?.map((s: any) => s.skill?.name || s.name || s).filter(Boolean) || [];
    const status = statusConfig[application.status] || statusConfig.pending;
    const matchScore = application.match_score;
    const waiting = getWaitingDays(application.applied_at);
    const router = useRouter();

    const [hoveredStar, setHoveredStar] = useState(0);
    const [rating, setRating] = useState(application.rating || 0);
    const [isRating, setIsRating] = useState(false);

    const handleRate = async (value: number) => {
        setIsRating(true);
        setRating(value);
        try {
            await updateApplicationRating(application.id, value);
            router.refresh();
        } catch (e) {
            console.error("Rating failed", e);
        } finally {
            setIsRating(false);
        }
    };

    return (
        <div
            className={`group relative bg-white rounded-xl border transition-all duration-200 hover:shadow-lg hover:border-primary/30 ${isSelected ? "border-primary shadow-md ring-2 ring-primary/10" : "border-slate-150 shadow-sm"
                }`}
        >
            {/* Main card body */}
            <div className="p-5">
                <div className="flex items-start gap-4">
                    {/* Checkbox */}
                    {onSelect && (
                        <div className="pt-1">
                            <input
                                type="checkbox"
                                checked={isSelected}
                                onChange={(e) => onSelect(application.id, e.target.checked)}
                                className="w-4 h-4 rounded border-slate-300 text-primary focus:ring-primary/30 cursor-pointer"
                            />
                        </div>
                    )}

                    {/* Avatar */}
                    <div className="relative flex-shrink-0">
                        <div className="w-12 h-12 rounded-full bg-gradient-to-br from-primary to-violet-500 flex items-center justify-center text-white text-lg font-bold shadow-md">
                            {candidate?.avatar_url ? (
                                <img
                                    src={candidate.avatar_url}
                                    alt={candidate.name}
                                    className="w-12 h-12 rounded-full object-cover"
                                />
                            ) : (
                                (candidate?.name || "U").charAt(0).toUpperCase()
                            )}
                        </div>
                        {/* New badge for unviewed */}
                        {!application.viewed_at && application.status === "pending" && (
                            <span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-orange-500 border-2 border-white" />
                        )}
                    </div>

                    {/* Candidate Info */}
                    <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between gap-3">
                            <div>
                                <Link
                                    href={`/dashboard/applications/${application.id}`}
                                    className="text-base font-bold text-slate-900 hover:text-primary transition-colors line-clamp-1"
                                >
                                    {candidate?.name || "Unknown Candidate"}
                                </Link>
                                <p className="text-sm text-slate-500 line-clamp-1">
                                    {profile?.headline || candidate?.email}
                                </p>
                            </div>

                            <div className="flex items-center gap-2 flex-shrink-0">
                                {/* Match Score Badge */}
                                {matchScore !== null && matchScore !== undefined && (
                                    <span
                                        className={`px-2.5 py-1 rounded-lg text-xs font-bold border ${getMatchBg(matchScore)} ${getMatchColor(matchScore)}`}
                                    >
                                        {Math.round(matchScore)}% match
                                    </span>
                                )}
                                {/* Status Badge */}
                                <span
                                    className={`px-2.5 py-1 rounded-lg text-xs font-bold border ${status.className}`}
                                >
                                    {status.label}
                                </span>
                            </div>
                        </div>

                        {/* Job Applied For */}
                        <div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
                            <span className="flex items-center gap-1">
                                <FileText className="w-3.5 h-3.5" />
                                Applied for: <strong className="text-slate-700">{job?.title}</strong>
                            </span>
                            <span className="flex items-center gap-1">
                                <Calendar className="w-3.5 h-3.5" />
                                {new Date(application.applied_at).toLocaleDateString("en-US", {
                                    month: "short",
                                    day: "numeric",
                                    year: "numeric",
                                })}
                            </span>
                            {profile?.location && (
                                <span className="flex items-center gap-1">
                                    <MapPin className="w-3.5 h-3.5" />
                                    {profile.location}
                                </span>
                            )}
                        </div>

                        {/* Skills */}
                        {skills.length > 0 && (
                            <div className="flex flex-wrap gap-1.5 mt-3">
                                {skills.slice(0, 4).map((skill: string, i: number) => (
                                    <span
                                        key={i}
                                        className="px-2 py-0.5 text-xs font-medium rounded-md bg-slate-100 text-slate-600 border border-slate-200/50"
                                    >
                                        {skill}
                                    </span>
                                ))}
                                {skills.length > 4 && (
                                    <span className="px-2 py-0.5 text-xs font-medium rounded-md bg-slate-100 text-slate-500">
                                        +{skills.length - 4} more
                                    </span>
                                )}
                            </div>
                        )}

                        {/* Tags */}
                        {application.tags && application.tags.length > 0 && (
                            <div className="flex flex-wrap gap-1.5 mt-2">
                                {application.tags.map((tag: string, i: number) => (
                                    <span
                                        key={i}
                                        className="px-2 py-0.5 text-xs font-semibold rounded-md bg-violet-50 text-violet-700 border border-violet-200/60 flex items-center gap-1"
                                    >
                                        <Tag className="w-2.5 h-2.5" />
                                        {tag}
                                    </span>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* Bottom Row: Rating, Waiting time, Attachments, Actions */}
                <div className="flex items-center justify-between mt-4 pt-3 border-t border-slate-100">
                    {/* Star Rating */}
                    <div className="flex items-center gap-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                            <button
                                key={star}
                                onClick={() => handleRate(star)}
                                onMouseEnter={() => setHoveredStar(star)}
                                onMouseLeave={() => setHoveredStar(0)}
                                disabled={isRating}
                                className="p-0.5 transition-transform hover:scale-110 disabled:opacity-50"
                            >
                                <Star
                                    className={`w-4 h-4 ${(hoveredStar || rating) >= star
                                        ? "fill-amber-400 text-amber-400"
                                        : "text-slate-300"
                                        } transition-colors`}
                                />
                            </button>
                        ))}
                    </div>

                    {/* Response time */}
                    <span className={`text-xs font-medium ${waiting.color}`}>
                        {waiting.days === 0
                            ? "Applied today"
                            : `${waiting.days}d waiting`}
                    </span>

                    {/* Attachments */}
                    <div className="flex items-center gap-2 text-slate-400">
                        {application.resume_url && (
                            <span title="Resume attached" className="flex items-center gap-1 text-xs">
                                <FileText className="w-3.5 h-3.5" /> Resume
                            </span>
                        )}
                        {application.cover_letter && (
                            <span title="Cover letter" className="flex items-center gap-1 text-xs">
                                <MessageSquare className="w-3.5 h-3.5" /> Letter
                            </span>
                        )}
                    </div>

                    {/* Quick Actions */}
                    <div className="flex items-center gap-1.5">
                        <Link
                            href={`/dashboard/applications/${application.id}`}
                            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-primary bg-primary/5 hover:bg-primary/10 rounded-lg transition-colors"
                        >
                            <Eye className="w-3.5 h-3.5" />
                            Review
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
