"use client";

import { useState } from "react";
import Link from "next/link";
import {
    ArrowLeft, Star, Calendar, MapPin, Mail, Phone,
    Linkedin, Globe, Award, Eye, MessageSquare, XCircle,
    CheckCircle, Clock
} from "lucide-react";
import { ApplicationStatusActions } from "../ApplicationStatusActions";
import { updateApplicationRating } from "@/app/actions/employerDashboard";
import { useRouter } from "next/navigation";
import { TagSelector } from "../TagSelector";

interface ApplicationHeaderProps {
    application: any;
    candidate: any;
    job: any;
    isEmployer: boolean;
}

function getMatchLabel(score: number) {
    if (score >= 85) return { label: "Excellent Match", color: "bg-emerald-500" };
    if (score >= 70) return { label: "Strong Fit", color: "bg-blue-500" };
    if (score >= 50) return { label: "Moderate Fit", color: "bg-amber-500" };
    return { label: "Low Match", color: "bg-red-500" };
}

export function ApplicationHeader({ application, candidate, job, isEmployer }: ApplicationHeaderProps) {
    const profile = candidate?.profile;
    const router = useRouter();
    const [rating, setRating] = useState(application.rating || 0);
    const [hoveredStar, setHoveredStar] = useState(0);

    const handleRate = async (value: number) => {
        setRating(value);
        try {
            await updateApplicationRating(application.id, value);
            router.refresh();
        } catch (e) {
            console.error("Failed to rate", e);
        }
    };

    const matchScore = application.match_score;
    const matchInfo = matchScore ? getMatchLabel(matchScore) : null;

    return (
        <div className="space-y-4">
            {/* Back button */}
            <Link
                href="/dashboard/applications"
                className="inline-flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-primary transition-colors"
            >
                <ArrowLeft className="h-4 w-4" />
                Back to Applications
            </Link>

            {/* Main Header Card */}
            <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
                {/* Gradient Banner */}
                <div className="h-2 bg-gradient-to-r from-primary via-violet-500 to-purple-600" />

                <div className="p-6">
                    <div className="flex flex-col lg:flex-row lg:items-start justify-between gap-6">
                        {/* Left: Candidate Info */}
                        <div className="flex items-start gap-5">
                            {/* Avatar */}
                            <div className="relative flex-shrink-0">
                                <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-primary to-violet-500 flex items-center justify-center text-white text-2xl font-bold shadow-lg shadow-primary/20">
                                    {candidate?.avatar_url ? (
                                        <img
                                            src={candidate.avatar_url}
                                            alt={candidate.name}
                                            className="w-20 h-20 rounded-2xl object-cover"
                                        />
                                    ) : (
                                        (candidate?.name || "U").charAt(0).toUpperCase()
                                    )}
                                </div>
                            </div>

                            <div>
                                <div className="flex items-center gap-3">
                                    <h1 className="text-2xl font-bold text-slate-900">
                                        {candidate?.name || "Unknown Candidate"}
                                    </h1>
                                    {/* Status badge */}
                                    {isEmployer && (
                                        <ApplicationStatusActions
                                            id={application.id}
                                            currentStatus={application.status}
                                        />
                                    )}
                                </div>

                                <div className="flex flex-col gap-2 mt-0.5">
                                    <p className="text-slate-500">
                                        {profile?.headline || candidate?.email}
                                    </p>
                                    {isEmployer && (
                                        <div className="mt-1">
                                            <TagSelector
                                                applicationId={application.id}
                                                currentTags={application.application_tags || []}
                                            />
                                        </div>
                                    )}
                                </div>

                                {/* Contact Info Bar */}
                                <div className="flex flex-wrap items-center gap-4 mt-3 text-sm text-slate-500">
                                    {candidate?.email && (
                                        <a
                                            href={`mailto:${candidate.email}`}
                                            className="flex items-center gap-1.5 hover:text-primary transition-colors"
                                        >
                                            <Mail className="w-3.5 h-3.5" />
                                            {candidate.email}
                                        </a>
                                    )}
                                    {profile?.phone && (
                                        <a
                                            href={`tel:${profile.phone}`}
                                            className="flex items-center gap-1.5 hover:text-primary transition-colors"
                                        >
                                            <Phone className="w-3.5 h-3.5" />
                                            {profile.phone}
                                        </a>
                                    )}
                                    {profile?.linkedin_url && (
                                        <a
                                            href={profile.linkedin_url}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="flex items-center gap-1.5 hover:text-primary transition-colors"
                                        >
                                            <Linkedin className="w-3.5 h-3.5" />
                                            LinkedIn
                                        </a>
                                    )}
                                    {profile?.portfolio_url && (
                                        <a
                                            href={profile.portfolio_url}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="flex items-center gap-1.5 hover:text-primary transition-colors"
                                        >
                                            <Globe className="w-3.5 h-3.5" />
                                            Portfolio
                                        </a>
                                    )}
                                    {profile?.location && (
                                        <span className="flex items-center gap-1.5">
                                            <MapPin className="w-3.5 h-3.5" />
                                            {profile.location}
                                        </span>
                                    )}
                                </div>

                                {/* Application Meta */}
                                <div className="flex items-center gap-4 mt-2 text-xs text-slate-400">
                                    <span className="flex items-center gap-1">
                                        <Calendar className="w-3 h-3" />
                                        Applied {new Date(application.applied_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                                    </span>
                                    <span>for <strong className="text-slate-600">{job?.title}</strong> at {job?.company}</span>
                                </div>
                            </div>
                        </div>

                        {/* Right: Match Score + Rating */}
                        <div className="flex flex-col items-end gap-3 flex-shrink-0">
                            {/* Match Score Circle */}
                            {matchScore !== null && matchScore !== undefined && (
                                <div className="flex items-center gap-3">
                                    <div className="relative w-20 h-20">
                                        <svg className="w-20 h-20 -rotate-90" viewBox="0 0 72 72">
                                            <circle
                                                cx="36" cy="36" r="30"
                                                fill="none" stroke="#e2e8f0" strokeWidth="6"
                                            />
                                            <circle
                                                cx="36" cy="36" r="30"
                                                fill="none"
                                                stroke={matchScore >= 85 ? "#10b981" : matchScore >= 70 ? "#3b82f6" : matchScore >= 50 ? "#f59e0b" : "#ef4444"}
                                                strokeWidth="6"
                                                strokeLinecap="round"
                                                strokeDasharray={`${(matchScore / 100) * 188.5} 188.5`}
                                                className="transition-all duration-700"
                                            />
                                        </svg>
                                        <span className="absolute inset-0 flex items-center justify-center text-lg font-bold text-slate-900">
                                            {Math.round(matchScore)}%
                                        </span>
                                    </div>
                                    <div>
                                        <p className="text-xs font-bold text-slate-500 uppercase tracking-wide">Match</p>
                                        {matchInfo && (
                                            <span className={`inline-block mt-1 px-2 py-0.5 rounded-full text-xs font-bold text-white ${matchInfo.color}`}>
                                                {matchInfo.label}
                                            </span>
                                        )}
                                    </div>
                                </div>
                            )}

                            {/* Star Rating */}
                            {isEmployer && (
                                <div className="flex items-center gap-1.5">
                                    <span className="text-xs font-semibold text-slate-500 mr-1">Rate:</span>
                                    {[1, 2, 3, 4, 5].map((star) => (
                                        <button
                                            key={star}
                                            onClick={() => handleRate(star)}
                                            onMouseEnter={() => setHoveredStar(star)}
                                            onMouseLeave={() => setHoveredStar(0)}
                                            className="p-0.5 transition-transform hover:scale-125"
                                        >
                                            <Star
                                                className={`w-5 h-5 ${(hoveredStar || rating) >= star
                                                    ? "fill-amber-400 text-amber-400"
                                                    : "text-slate-300"
                                                    } transition-colors`}
                                            />
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
