import { User } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getRecommendedJobs } from "@/lib/recommendations";
import Link from "next/link";
import { Sparkles, MapPin, Briefcase, DollarSign, Clock, Filter } from "lucide-react";

export default async function JobMatchesPage(props: { searchParams: Promise<{ sort?: string }> }) {
    const searchParams = await props.searchParams;
    const currentUser = await getCurrentUser();

    if (!currentUser || currentUser.role !== 'candidate') {
        redirect("/dashboard");
    }

    const candidateProfile = { ...currentUser, skills: currentUser.skills || [] } as User;
    const recommendations = await getRecommendedJobs(candidateProfile);

    // Sort by match score (default) or other criteria
    const sortBy = searchParams.sort || 'score';
    const sortedRecommendations = [...recommendations].sort((a, b) => {
        if (sortBy === 'score') return b.matchScore - a.matchScore;
        if (sortBy === 'salary') return (b.salaryMax || 0) - (a.salaryMax || 0);
        if (sortBy === 'recent') return new Date(b.postedAt).getTime() - new Date(a.postedAt).getTime();
        return 0;
    });

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900">Job Matches</h1>
                    <p className="text-slate-600 mt-2">
                        {recommendations.length} jobs matched to your profile
                    </p>
                </div>

                {/* Sort Options */}
                <div className="flex items-center gap-2 bg-slate-100 p-1 rounded-lg">
                    <Link
                        href="/dashboard/matches?sort=score"
                        className={`px-4 py-2 rounded-md text-sm font-semibold transition-colors ${sortBy === 'score'
                            ? 'bg-white text-primary shadow-sm'
                            : 'text-slate-600 hover:text-slate-900'
                            }`}
                    >
                        Best Match
                    </Link>
                    <Link
                        href="/dashboard/matches?sort=salary"
                        className={`px-4 py-2 rounded-md text-sm font-semibold transition-colors ${sortBy === 'salary'
                            ? 'bg-white text-primary shadow-sm'
                            : 'text-slate-600 hover:text-slate-900'
                            }`}
                    >
                        Highest Salary
                    </Link>
                    <Link
                        href="/dashboard/matches?sort=recent"
                        className={`px-4 py-2 rounded-md text-sm font-semibold transition-colors ${sortBy === 'recent'
                            ? 'bg-white text-primary shadow-sm'
                            : 'text-slate-600 hover:text-slate-900'
                            }`}
                    >
                        Most Recent
                    </Link>
                </div>
            </div>

            {/* Empty State */}
            {recommendations.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-16 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50">
                    <Sparkles className="h-12 w-12 text-slate-400 mb-4" />
                    <h3 className="text-lg font-bold text-slate-900">No matches yet</h3>
                    <p className="text-sm text-slate-500 mt-2 max-w-md text-center">
                        Complete your profile and add skills to get personalized job recommendations.
                    </p>
                    <Link
                        href="/dashboard/profile/edit"
                        className="mt-4 px-6 py-2 bg-primary text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
                    >
                        Complete Profile
                    </Link>
                </div>
            ) : (
                <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                    {sortedRecommendations.map((job) => (
                        <div
                            key={job.id}
                            className="group relative rounded-2xl border border-slate-100 bg-white p-6 shadow-sm transition-all hover:border-primary/50 hover:shadow-md"
                        >
                            <Link href={`/jobs/${job.id}`} className="block">
                                {/* Match Score Badge */}
                                {job.matchScore > 0 && (
                                    <div className="absolute top-4 right-4">
                                        <span className={`flex items-center gap-1 rounded-full px-3 py-1 text-xs font-bold ${job.matchScore >= 80 ? 'bg-emerald-50 text-emerald-600' :
                                            job.matchScore >= 60 ? 'bg-blue-50 text-blue-600' :
                                                'bg-amber-50 text-amber-600'
                                            }`}>
                                            <Sparkles className="h-3 w-3" /> {job.matchScore}% Match
                                        </span>
                                    </div>
                                )}

                                {/* Company Logo Placeholder */}
                                <div className="h-12 w-12 rounded-lg bg-slate-100 font-bold text-slate-400 flex items-center justify-center text-lg">
                                    {job.company.charAt(0)}
                                </div>

                                {/* Job Details */}
                                <h3 className="mt-4 font-bold text-slate-900 group-hover:text-primary transition-colors line-clamp-1">
                                    {job.title}
                                </h3>
                                <p className="text-sm text-slate-600 mt-1">{job.company}</p>

                                <div className="mt-4 space-y-2">
                                    <div className="flex items-center gap-2 text-sm text-slate-500">
                                        <MapPin className="h-4 w-4" />
                                        {job.location}
                                    </div>
                                    <div className="flex items-center gap-2 text-sm text-slate-500">
                                        <Briefcase className="h-4 w-4" />
                                        {job.type}
                                    </div>
                                    {job.salaryMin && job.salaryMax && (
                                        <div className="flex items-center gap-2 text-sm text-slate-500">
                                            <DollarSign className="h-4 w-4" />
                                            ${(job.salaryMin / 1000).toFixed(0)}k - ${(job.salaryMax / 1000).toFixed(0)}k
                                        </div>
                                    )}
                                    <div className="flex items-center gap-2 text-sm text-slate-500">
                                        <Clock className="h-4 w-4" />
                                        {new Date(job.postedAt).toLocaleDateString()}
                                    </div>
                                </div>

                                {/* Skills */}
                                {job.skills && job.skills.length > 0 && (
                                    <div className="mt-4 flex flex-wrap gap-2">
                                        {job.skills.slice(0, 3).map((skill) => (
                                            <span
                                                key={skill}
                                                className="px-2 py-1 rounded-md bg-slate-50 text-xs font-medium text-slate-600"
                                            >
                                                {skill}
                                            </span>
                                        ))}
                                        {job.skills.length > 3 && (
                                            <span className="px-2 py-1 text-xs font-medium text-slate-400">
                                                +{job.skills.length - 3} more
                                            </span>
                                        )}
                                    </div>
                                )}
                            </Link>

                            {/* Apply Button */}
                            <div className="mt-6 pt-4 border-t border-slate-100">
                                <Link
                                    href={`/jobs/${job.id}/apply`}
                                    className="block w-full text-center px-4 py-2 bg-primary text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
                                >
                                    Apply Now
                                </Link>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
