"use client";

import { Bookmark, Clock, MapPin, Users, Briefcase, DollarSign, Zap, Share2, ChevronRight } from "lucide-react";
import Link from "next/link";
import { cn, getRelativeTime } from "@/lib/utils";
import { useEffect, useState } from "react";

interface JobCardProps {
    id: string;
    title: string;
    company: string;
    location: string;
    type: string;
    salaryMin?: number;
    salaryMax?: number;
    currency?: string;
    hideSalary?: boolean;
    postedAt: string;
    description?: string;
    skills?: string[];
    applicants?: number;
    featured?: boolean;
    isSaved?: boolean;
    employerId?: string;
    experienceLevel?: string | null;
    workLocationType?: string | null;
    variant?: "list" | "grid";
    baseUrl?: string;
    matchScore?: number;
    isVerified?: boolean;
    isQuickApply?: boolean;
}

const EXPERIENCE_LABELS: Record<string, string> = {
    entry: "Entry Level",
    mid: "Mid Level",
    senior: "Senior",
    executive: "Executive",
};

const LOCATION_TYPE_ICONS: Record<string, string> = {
    remote: "🏠",
    "on-site": "🏢",
    hybrid: "🔄",
};

function formatSalary(amount: number, currency: string = "NGN") {
    if (amount >= 1000000) return `${currency === "NGN" ? "₦" : "$"}${(amount / 1000000).toFixed(1)}M`;
    if (amount >= 1000) return `${currency === "NGN" ? "₦" : "$"}${(amount / 1000).toFixed(0)}k`;
    return `${currency === "NGN" ? "₦" : "$"}${amount.toLocaleString()}`;
}

function getMatchScoreDisplay(score: number) {
    if (score >= 85) return { color: "bg-green-50 text-green-700 border-green-200", icon: "🟢" };
    if (score >= 70) return { color: "bg-amber-50 text-amber-700 border-amber-200", icon: "🟡" };
    return { color: "bg-slate-50 text-slate-700 border-slate-200", icon: "⚪" };
}

export function JobCard({
    id,
    title,
    company,
    location,
    type,
    salaryMin,
    salaryMax,
    currency = "NGN",
    hideSalary = false,
    postedAt,
    description,
    skills,
    applicants,
    featured,
    isSaved = false,
    employerId,
    experienceLevel,
    workLocationType,
    variant = "list",
    baseUrl = "/jobs",
    matchScore,
    isVerified,
    isQuickApply,
}: JobCardProps) {
    const [relativeTime, setRelativeTime] = useState<string>("");
    const [saved, setSaved] = useState(isSaved);
    const [loading, setLoading] = useState(false);
    const [showShare, setShowShare] = useState(false);

    useEffect(() => {
        setRelativeTime(getRelativeTime(postedAt));
        const interval = setInterval(() => setRelativeTime(getRelativeTime(postedAt)), 60000);
        return () => clearInterval(interval);
    }, [postedAt]);

    const isNew = new Date(postedAt).getTime() > Date.now() - 48 * 60 * 60 * 1000;

    const handleSave = async (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setLoading(true);
        setSaved(!saved);
        try {
            await import("@/app/actions/jobActions").then(mod => mod.toggleSaveJobAction(id));
        } catch (error) {
            console.error("Failed to toggle job save state:", error);
            setSaved(!saved);
        } finally {
            setLoading(false);
        }
    };

    const handleShare = async (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        const url = `${window.location.origin}${baseUrl}/${id}`;
        try {
            await navigator.clipboard.writeText(url);
            setShowShare(true);
            setTimeout(() => setShowShare(false), 2000);
        } catch (error) {
            console.error("Failed to copy link to clipboard:", error);
        }
    };

    // ---------- GRID VARIANT ----------
    if (variant === "grid") {
        return (
            <Link
                href={`${baseUrl}/${id}`}
                className={cn(
                    "group relative flex flex-col rounded-xl border bg-white p-5 shadow-sm transition-all hover:shadow-md hover:border-blue-200",
                    featured && "ring-1 ring-blue-100 border-blue-200"
                )}
            >
                {/* Header */}
                <div className="flex items-start gap-3 mb-3">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-slate-50 to-slate-100 font-bold text-sm text-slate-500 border border-slate-200">
                        {company.charAt(0)}
                    </div>
                    <div className="flex-1 min-w-0">
                        <h3 className="text-sm font-bold text-slate-900 group-hover:text-blue-600 transition-colors truncate">
                            {title}
                        </h3>
                        <p className="text-xs text-slate-500 truncate flex items-center gap-1">
                            {company}
                            {isVerified && (
                                <svg className="h-3 w-3 text-blue-500" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                                </svg>
                            )}
                        </p>
                    </div>
                </div>

                {/* Badges */}
                <div className="flex flex-wrap gap-1.5 mb-3">
                    {isNew && (
                        <span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2 py-0.5 text-[10px] font-bold text-green-700 border border-green-100">
                            <Zap className="h-2.5 w-2.5" /> NEW
                        </span>
                    )}
                    {featured && (
                        <span className="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold text-amber-700 border border-amber-100">
                            FEATURED
                        </span>
                    )}
                    <span className="rounded-full bg-slate-50 px-2 py-0.5 text-[10px] font-medium text-slate-600 border border-slate-100 capitalize">
                        {type.replace("-", " ")}
                    </span>
                    {workLocationType && (
                        <span className="rounded-full bg-slate-50 px-2 py-0.5 text-[10px] font-medium text-slate-600 border border-slate-100">
                            {LOCATION_TYPE_ICONS[workLocationType] || ""} {workLocationType.replace("-", " ")}
                        </span>
                    )}
                    {matchScore !== undefined && (
                        <span className={cn("rounded-full px-2 py-0.5 text-[10px] font-bold border", getMatchScoreDisplay(matchScore).color)}>
                            {getMatchScoreDisplay(matchScore).icon} {matchScore}% Match
                        </span>
                    )}
                </div>

                {/* Location & salary */}
                <div className="space-y-1.5 mb-3 text-xs text-slate-600">
                    <div className="flex items-center gap-1.5">
                        <MapPin className="h-3 w-3 text-slate-400" /> {location}
                    </div>
                    {!hideSalary && (salaryMin || salaryMax) && (
                        <div className="flex items-center gap-1.5 text-slate-800 font-semibold">
                            <DollarSign className="h-3 w-3 text-slate-400" />
                            {salaryMin && formatSalary(salaryMin, currency)}
                            {salaryMin && salaryMax && " – "}
                            {salaryMax && formatSalary(salaryMax, currency)}
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="mt-auto pt-3 border-t border-slate-50 flex items-center justify-between">
                    <span className="text-[10px] text-slate-400">{relativeTime}</span>
                    <span className="inline-flex items-center gap-1 text-xs font-semibold text-blue-600 group-hover:text-blue-700">
                        View <ChevronRight className="h-3 w-3" />
                    </span>
                </div>
            </Link>
        );
    }

    // ---------- LIST VARIANT (default) ----------
    return (
        <Link
            href={`${baseUrl}/${id}`}
            className={cn(
                "group relative flex flex-col gap-4 rounded-xl border border-slate-100 bg-white p-6 shadow-sm transition-all hover:border-blue-200 hover:shadow-md",
                featured && "ring-1 ring-blue-50 border-l-4 border-l-blue-500"
            )}
        >
            {/* Top row */}
            <div className="flex items-start justify-between">
                <div className="flex gap-4">
                    <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-slate-50 to-slate-100 text-lg font-bold text-slate-500 border border-slate-200">
                        {company.charAt(0)}
                    </div>
                    <div>
                        <div className="flex items-center gap-2 flex-wrap">
                            <h3 className="text-lg font-bold text-slate-900 group-hover:text-blue-600 transition-colors">
                                {title}
                            </h3>
                            {isNew && (
                                <span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2 py-0.5 text-[10px] font-bold text-green-700 border border-green-100">
                                    <Zap className="h-2.5 w-2.5" /> NEW
                                </span>
                            )}
                            {featured && (
                                <span className="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold text-amber-700 border border-amber-100">
                                    FEATURED
                                </span>
                            )}
                            {matchScore !== undefined && (
                                <span className={cn("rounded-full px-2.5 py-0.5 text-[10px] font-bold border shadow-sm", getMatchScoreDisplay(matchScore).color)}>
                                    {getMatchScoreDisplay(matchScore).icon} {matchScore}% Match
                                </span>
                            )}
                            {isQuickApply && (
                                <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[10px] font-bold text-blue-600 border border-blue-100">
                                    ⚡ Quick Apply
                                </span>
                            )}
                        </div>
                        {employerId ? (
                            <span
                                role="link"
                                tabIndex={0}
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    window.location.href = `/profiles/employer/${employerId}`;
                                }}
                                className="text-sm font-medium text-slate-500 hover:text-blue-600 transition-colors cursor-pointer flex items-center gap-1"
                            >
                                {company}
                                {isVerified && (
                                    <span title="Verified Employer">
                                        <svg className="h-3.5 w-3.5 text-blue-500" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                                        </svg>
                                    </span>
                                )}
                            </span>
                        ) : (
                            <p className="text-sm font-medium text-slate-500 flex items-center gap-1">
                                {company}
                                {isVerified && (
                                    <span title="Verified Employer">
                                        <svg className="h-3.5 w-3.5 text-blue-500" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                                        </svg>
                                    </span>
                                )}
                            </p>
                        )}
                    </div>
                </div>

                <div className="flex items-center gap-1">
                    <button
                        onClick={handleShare}
                        className="relative p-2 rounded-full text-slate-300 hover:text-blue-500 hover:bg-blue-50 transition-all"
                        aria-label="Share job"
                    >
                        <Share2 className="h-4 w-4" />
                        {showShare && (
                            <span className="absolute -top-8 left-1/2 -translate-x-1/2 rounded bg-slate-900 px-2 py-1 text-[10px] text-white whitespace-nowrap">
                                Link copied!
                            </span>
                        )}
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={loading}
                        className={cn(
                            "transition-colors hover:text-blue-500 p-2 rounded-full hover:bg-blue-50",
                            saved ? "text-blue-500" : "text-slate-300"
                        )}
                        aria-label={saved ? "Unsave job" : "Save job"}
                    >
                        <Bookmark className={cn("h-5 w-5", saved && "fill-current")} />
                    </button>
                </div>
            </div>

            {/* Description */}
            {description && (
                <p className="line-clamp-2 text-sm text-slate-600 leading-relaxed">{description}</p>
            )}

            {/* Skills */}
            {skills && skills.length > 0 && (
                <div className="flex flex-wrap gap-1.5">
                    {skills.slice(0, 6).map((skill) => (
                        <span key={skill} className="rounded-md bg-blue-50/70 px-2.5 py-1 text-xs font-medium text-blue-700 border border-blue-100/50">
                            {skill}
                        </span>
                    ))}
                    {skills.length > 6 && (
                        <span className="rounded-md bg-slate-50 px-2.5 py-1 text-xs font-medium text-slate-500">
                            +{skills.length - 6} more
                        </span>
                    )}
                </div>
            )}

            {/* Metadata */}
            <div className="mt-1 flex flex-wrap items-center gap-3 border-t border-slate-50 pt-4 text-xs font-medium text-slate-500">
                <span className="flex items-center gap-1.5 rounded-full bg-slate-50 px-2.5 py-1 capitalize">
                    <Briefcase className="h-3.5 w-3.5 text-slate-400" /> {type.replace("-", " ")}
                </span>
                {workLocationType && (
                    <span className="flex items-center gap-1.5 rounded-full bg-slate-50 px-2.5 py-1 capitalize">
                        {LOCATION_TYPE_ICONS[workLocationType] || "📍"} {workLocationType.replace("-", " ")}
                    </span>
                )}
                <span className="flex items-center gap-1.5 rounded-full bg-slate-50 px-2.5 py-1">
                    <MapPin className="h-3.5 w-3.5 text-slate-400" /> {location}
                </span>
                {experienceLevel && (
                    <span className="flex items-center gap-1.5 rounded-full bg-slate-50 px-2.5 py-1">
                        {EXPERIENCE_LABELS[experienceLevel] || experienceLevel}
                    </span>
                )}
                {!hideSalary && (salaryMin || salaryMax) && (
                    <span className="flex items-center gap-1.5 font-semibold text-slate-700">
                        <DollarSign className="h-3.5 w-3.5 text-slate-400" />
                        {salaryMin && formatSalary(salaryMin, currency)}
                        {salaryMin && salaryMax && " – "}
                        {salaryMax && formatSalary(salaryMax, currency)}
                    </span>
                )}
                <span className="ml-auto flex items-center gap-1.5 text-slate-400">
                    <Clock className="h-3.5 w-3.5" /> {relativeTime || "Loading..."}
                </span>
                {applicants !== undefined && applicants > 0 && (
                    <span className="flex items-center gap-1 text-blue-600">
                        <Users className="h-3.5 w-3.5" /> {applicants} applicant{applicants !== 1 && "s"}
                    </span>
                )}
            </div>
        </Link>
    );
}
