"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Sparkles, ArrowRight, ThumbsUp, ThumbsDown, Briefcase, MapPin, Building } from "lucide-react";

interface Job {
    id: string;
    title: string;
    company: string;
    location: string;
    matchScore: number;
    matchReasons: string[];
    isVerified?: boolean;
    salaryMin?: number;
    type: string;
}

export function RecommendationsWidget() {
    const [jobs, setJobs] = useState<Job[]>([]);
    const [loading, setLoading] = useState(true);
    const [hiddenJobs, setHiddenJobs] = useState<Set<string>>(new Set());

    useEffect(() => {
        // Fetch recommendations on mount
        const fetchRecs = async () => {
            try {
                // We'll mock the endpoint response format for now, later integrated with the real API
                const res = await fetch("/api/recommendations?limit=4");
                if (res.ok) {
                    const data = await res.json();
                    setJobs(data.recommendations || []);
                }
            } catch (error) {
                console.error("Failed to load recommendations", error);
            } finally {
                setLoading(false);
            }
        };
        fetchRecs();
    }, []);

    const handleFeedback = async (jobId: string, isPositive: boolean) => {
        if (!isPositive) {
            setHiddenJobs((prev) => new Set(prev).add(jobId));
        }
        // In the future: send feedback to /api/recommendations/feedback to train the ML model
        try {
            await fetch("/api/recommendations/feedback", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ jobId, isPositive }),
            });
        } catch (error) {
            console.error("Recommendations feedback error:", error);
        }
    };

    if (loading) {
        return (
            <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm animate-pulse">
                <div className="flex items-center gap-3 mb-6">
                    <div className="h-10 w-10 rounded-xl bg-slate-200" />
                    <div className="space-y-2">
                        <div className="h-5 w-48 bg-slate-200 rounded" />
                        <div className="h-3 w-32 bg-slate-100 rounded" />
                    </div>
                </div>
                <div className="space-y-3">
                    {[1, 2, 3].map((i) => (
                        <div key={i} className="h-24 bg-slate-50 rounded-xl border border-slate-100" />
                    ))}
                </div>
            </div>
        );
    }

    if (jobs.length === 0) {
        return (
            <div className="rounded-2xl border border-slate-200 bg-white p-6 text-center shadow-sm">
                <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-blue-50 mb-4">
                    <Sparkles className="h-8 w-8 text-blue-500" />
                </div>
                <h3 className="text-lg font-bold text-slate-900 mb-1">We&apos;re learning what you like</h3>
                <p className="text-sm text-slate-500 mb-5 max-w-xs mx-auto">
                    Complete your profile and save a few jobs to get personalized recommendations.
                </p>
                <Link
                    href="/dashboard/profile"
                    className="inline-flex rounded-xl bg-blue-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-blue-700 transition-colors shadow-lg shadow-blue-500/20"
                >
                    Update Profile
                </Link>
            </div>
        );
    }

    const visibleJobs = jobs.filter((job) => !hiddenJobs.has(job.id)).slice(0, 3);

    return (
        <div className="rounded-2xl border border-slate-200 bg-white p-0 shadow-sm overflow-hidden flex flex-col h-full">
            {/* Header */}
            <div className="bg-gradient-to-r from-blue-700 to-indigo-800 p-6 text-white relative overflow-hidden shrink-0">
                <div className="absolute inset-0 opacity-10 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48cGF0dGVybiBpZD0iYSIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIj48cGF0aCBkPSJNMCAyMGgyME0yMCAwdjIwIiBmaWxsPSJub25lIiBzdHJva2U9InJnYmEoMjU1LDI1NSwyNTUsMC4wNSkiIHN0cm9rZS13aWR0aD0iMSIvPjwvcGF0dGVybj48L2RlZnM+PHJlY3QgZmlsbD0idXJsKCNhKSIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIvPjwvc3ZnPg==')] " />
                <div className="relative z-10 flex items-center justify-between">
                    <div>
                        <h2 className="text-lg font-bold flex items-center gap-2">
                            <Sparkles className="h-5 w-5 text-amber-300" />
                            Top Picks for You
                        </h2>
                        <p className="text-sm text-blue-100/80 mt-1">Based on your skills & activity</p>
                    </div>
                    <Link
                        href="/dashboard/recommendations"
                        className="p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
                        title="View all recommendations"
                    >
                        <ArrowRight className="h-5 w-5" />
                    </Link>
                </div>
            </div>

            {/* Job List */}
            <div className="flex-1 overflow-y-auto">
                {visibleJobs.length > 0 ? (
                    <div className="divide-y divide-slate-100">
                        {visibleJobs.map((job) => (
                            <Link
                                key={job.id}
                                href={`/jobs/${job.id}`}
                                className="block group p-5 hover:bg-slate-50 transition-colors relative"
                            >
                                <div className="flex justify-between items-start gap-4 mb-2">
                                    <div className="min-w-0">
                                        <h3 className="font-bold text-slate-900 group-hover:text-blue-600 truncate transition-colors">
                                            {job.title}
                                        </h3>
                                        <div className="flex items-center gap-1.5 text-xs text-slate-500 mt-1">
                                            <span className="flex items-center gap-1">
                                                <Building className="h-3 w-3" /> {job.company}
                                            </span>
                                            <span className="text-slate-300">•</span>
                                            <span className="flex items-center gap-1">
                                                <MapPin className="h-3 w-3" /> {job.location}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="shrink-0 flex flex-col items-end">
                                        <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold border shadow-sm ${job.matchScore >= 85 ? "bg-green-50 text-green-700 border-green-200" :
                                            job.matchScore >= 70 ? "bg-amber-50 text-amber-700 border-amber-200" :
                                                "bg-slate-50 text-slate-600 border-slate-200"
                                            }`}>
                                            {job.matchScore >= 85 ? "🟢" : job.matchScore >= 70 ? "🟡" : "⚪"}
                                            {job.matchScore}% Match
                                        </span>
                                    </div>
                                </div>

                                <p className="text-xs text-slate-500 line-clamp-1 mb-3">
                                    {job.matchReasons.join(" • ")}
                                </p>

                                {/* Feedback Actions (Overlay on hover) */}
                                <div className="absolute bottom-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1.5 bg-white/90 backdrop-blur pb-1 pl-2 rounded-tl-lg">
                                    <button
                                        onClick={(e) => { e.preventDefault(); handleFeedback(job.id, true); }}
                                        className="p-1.5 rounded-lg text-slate-400 hover:text-green-600 hover:bg-green-50 transition-colors"
                                        title="Show more like this"
                                    >
                                        <ThumbsUp className="h-4 w-4" />
                                    </button>
                                    <button
                                        onClick={(e) => { e.preventDefault(); handleFeedback(job.id, false); }}
                                        className="p-1.5 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                                        title="Show less like this"
                                    >
                                        <ThumbsDown className="h-4 w-4" />
                                    </button>
                                </div>
                            </Link>
                        ))}
                    </div>
                ) : (
                    <div className="p-8 text-center text-slate-500 text-sm">
                        You've hidden all current recommendations. Check back later for more!
                    </div>
                )}
            </div>

            <div className="p-4 border-t border-slate-100 bg-slate-50/50 mt-auto shrink-0">
                <Link
                    href="/dashboard/recommendations"
                    className="flex w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors"
                >
                    View All Recommendations <ArrowRight className="h-4 w-4" />
                </Link>
            </div>
        </div>
    );
}
