"use client";

import { JobProgress } from "@/components/dashboard/JobProgress";
import {
    Bookmark, Search, MapPin, Briefcase, TrendingUp, Sparkles,
    Loader2, X, ChevronRight, CheckCircle2, Clock, XCircle,
    MessageSquare, Calendar, FileText, ArrowRight
} from "lucide-react";
import Link from "next/link";
import { Job } from "@/lib/db";
import { toggleSaveJobAction } from "@/app/actions/jobActions";
import { motion } from "framer-motion";
import { useState } from "react";
import {
    ProfileCompletionWidget,
    JobSearchWidget,
    CareerInsightsWidget,
    ProfileViewsWidget,
    LearningResourcesWidget,
    SkillsAssessmentWidget
} from "@/components/dashboard/widgets/CandidateWidgets";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";

interface CandidateStats {
    totalApplications: number;
    inReview: number;
    interviewing: number;
    offered: number;
    rejected: number;
}

interface RecentApplication {
    id: string;
    company: string;
    role: string;
    status: string;
    date: string;
}

interface UpcomingInterview {
    id: string;
    title: string;
    company: string;
    type: string;
    scheduledAt: string;
    videoLink?: string;
}

interface CandidateDashboardProps {
    user?: { id?: string; name?: string; firstName?: string; skills?: string[] };
    recommendations: (Job & { matchScore: number })[];
    savedJobs?: Job[];
    profileCompletion?: number;
    completionTips?: { label: string; done: boolean }[];
    stats?: CandidateStats;
    recentApplications?: RecentApplication[];
    upcomingInterviews?: UpcomingInterview[];
}

export function CandidateDashboard({
    user,
    recommendations,
    savedJobs = [],
    profileCompletion = 0,
    completionTips = [],
    stats,
    recentApplications = [],
    upcomingInterviews = [],
}: CandidateDashboardProps) {
    const displayName = user?.firstName || (user?.name?.split(" ")[0]) || "there";
    const firstMissingTip = completionTips.find((t) => !t.done)?.label ?? "Complete your profile to increase visibility";

    // Animation variants
    const containerVariants = {
        hidden: { opacity: 0 },
        show: {
            opacity: 1,
            transition: { staggerChildren: 0.1 }
        }
    };

    const itemVariants = {
        hidden: { opacity: 0, y: 20 },
        show: { opacity: 1, y: 0, transition: { type: "spring" as const, stiffness: 300, damping: 24 } }
    };

    return (
        <motion.div
            className="space-y-6"
            variants={containerVariants}
            initial="hidden"
            animate="show"
        >
            {/* Level 1: Critical Stats & Profile */}
            <div className="grid gap-6 md:grid-cols-12">
                {/* Profile Completion Card */}
                <motion.div variants={itemVariants} className="md:col-span-8 lg:col-span-8 xl:col-span-5">
                    <Card className="relative overflow-hidden">
                        <div className="absolute top-0 left-0 w-2 h-full bg-primary" />
                        <CardContent className="pl-8 pt-6 pb-6">
                            <div className="flex justify-between items-end mb-4">
                                <div>
                                    <h2 className="text-xl font-bold text-slate-900">Welcome back, {displayName}! 👋</h2>
                                    <p className="text-sm text-slate-500 mt-1">Here is what is happening with your job search.</p>
                                </div>
                                <span className="text-2xl font-black text-primary">{profileCompletion}%</span>
                            </div>

                            <div className="space-y-2">
                                <div className="flex justify-between text-xs font-semibold text-slate-600 uppercase tracking-wider">
                                    <span>Profile Strength</span>
                                    <span>{profileCompletion < 40 ? "Beginner" : profileCompletion < 70 ? "Intermediate" : profileCompletion < 90 ? "Advanced" : "Expert"}</span>
                                </div>
                                <Progress value={profileCompletion} className="h-2.5" />
                                <p className="text-sm flex items-center gap-2 mt-4 text-slate-600 bg-slate-50 p-3 rounded-xl border border-slate-100">
                                    <Sparkles className="h-4 w-4 text-amber-500" />
                                    {firstMissingTip}
                                    <Link href="/dashboard/profile" className="ml-auto text-primary font-semibold hover:underline">Complete</Link>
                                </p>
                            </div>
                        </CardContent>
                    </Card>
                </motion.div>

                {/* Quick Stats — Real data */}
                <motion.div variants={itemVariants} className="md:col-span-4 lg:col-span-4 xl:col-span-7 grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard
                        title="Applications"
                        value={stats?.totalApplications?.toString() || "0"}
                        icon={<Briefcase className="h-5 w-5 text-blue-600" />}
                        bg="bg-blue-50"
                        action="View All"
                        href="/dashboard/applications"
                    />
                    <StatCard
                        title="Interviews"
                        value={stats?.interviewing?.toString() || "0"}
                        icon={<Calendar className="h-5 w-5 text-indigo-600" />}
                        bg="bg-indigo-50"
                        status={upcomingInterviews.length > 0 ? "Upcoming" : undefined}
                    />
                    <StatCard
                        title="In Review"
                        value={stats?.inReview?.toString() || "0"}
                        icon={<Clock className="h-5 w-5 text-amber-600" />}
                        bg="bg-amber-50"
                        status="Pending"
                    />
                    <StatCard
                        title="Offers"
                        value={stats?.offered?.toString() || "0"}
                        icon={<CheckCircle2 className="h-5 w-5 text-emerald-600" />}
                        bg="bg-emerald-50"
                        status={stats?.offered ? "Congratulations!" : undefined}
                    />
                </motion.div>
            </div>

            <div className="grid gap-6 lg:grid-cols-3">
                {/* Main Content (Left Column) */}
                <div className="lg:col-span-2 space-y-6">
                    <JobSearchWidget />
                    <motion.section variants={itemVariants}>
                        <div className="mb-4 flex items-center justify-between">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Sparkles className="h-5 w-5 text-indigo-500" /> Recommended For You
                            </h2>
                            <Link href="/dashboard/matches" className="text-sm font-semibold text-primary hover:text-primary/80 flex items-center">
                                View all <ChevronRight className="h-4 w-4" />
                            </Link>
                        </div>

                        {recommendations.length > 0 ? (
                            <div className="grid gap-4 sm:grid-cols-2">
                                {recommendations.slice(0, 4).map((job, idx) => (
                                    <JobCard key={`rec-${job.id}-${idx}`} job={job} user={user} />
                                ))}
                            </div>
                        ) : (
                            <Card>
                                <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                                    <Sparkles className="h-10 w-10 text-slate-300 mb-3" />
                                    <p className="font-semibold text-slate-700 mb-1">No recommendations yet</p>
                                    <p className="text-sm text-slate-500 mb-4">Complete your profile and add skills to get personalized job matches.</p>
                                    <Button asChild variant="outline" size="sm">
                                        <Link href="/dashboard/profile">Complete Profile</Link>
                                    </Button>
                                </CardContent>
                            </Card>
                        )}
                    </motion.section>

                    {/* RECENT APPLICATIONS — Real Data */}
                    <motion.section variants={itemVariants}>
                        <Card>
                            <CardHeader className="flex flex-row items-center justify-between pb-2">
                                <CardTitle className="text-lg flex items-center gap-2">
                                    <FileText className="h-5 w-5 text-slate-400" /> Recent Applications
                                </CardTitle>
                                <Link href="/dashboard/applications" className="text-sm font-semibold text-primary hover:text-primary/80">View all</Link>
                            </CardHeader>
                            <CardContent>
                                {recentApplications.length > 0 ? (
                                    <JobProgress applications={recentApplications} />
                                ) : (
                                    <div className="flex flex-col items-center justify-center py-10 text-center">
                                        <FileText className="h-10 w-10 text-slate-300 mb-3" />
                                        <p className="font-semibold text-slate-700 mb-1">No applications yet</p>
                                        <p className="text-sm text-slate-500">Start applying to jobs to track your progress here.</p>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </motion.section>

                    {/* SAVED JOBS */}
                    {savedJobs.length > 0 && (
                        <motion.section variants={itemVariants}>
                            <div className="mb-4 flex items-center justify-between">
                                <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                    <Bookmark className="h-5 w-5 text-rose-500" /> Saved Jobs ({savedJobs.length})
                                </h2>
                            </div>
                            <div className="grid gap-4 sm:grid-cols-2">
                                {savedJobs.slice(0, 2).map((job) => (
                                    <JobCard key={`saved-${job.id}`} job={job} user={user} isSaved />
                                ))}
                            </div>
                        </motion.section>
                    )}
                </div>

                {/* Right Column (Secondary / Contextual Info) */}
                <div className="space-y-6">
                    <ProfileCompletionWidget completion={profileCompletion} />

                    {/* UPCOMING INTERVIEWS — Real Data */}
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-lg flex items-center gap-2">
                                <Calendar className="h-5 w-5 text-indigo-500" /> Upcoming Interviews
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            {upcomingInterviews.length > 0 ? (
                                <div className="space-y-4">
                                    {upcomingInterviews.map((interview, idx) => {
                                        const date = new Date(interview.scheduledAt);
                                        const isToday = new Date().toDateString() === date.toDateString();
                                        return (
                                            <div key={interview.id} className={`relative pl-6 pb-4 border-l-2 ${idx === 0 ? "border-indigo-100" : "border-slate-100"} last:pb-0 last:border-transparent`}>
                                                <div className={`absolute -left-[9px] top-0 h-4 w-4 rounded-full ${idx === 0 ? "bg-indigo-500" : "bg-slate-200"} border-4 border-white shadow-sm`} />
                                                <div className={idx === 0 ? "bg-slate-50 p-4 rounded-xl border border-slate-100 hover:border-indigo-200 transition-colors" : "p-2 pt-0"}>
                                                    <p className={`text-sm font-bold ${idx === 0 ? "text-indigo-700" : "text-slate-600"}`}>
                                                        {isToday ? "Today" : date.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, {date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" })}
                                                    </p>
                                                    <p className={`${idx === 0 ? "text-base" : "text-sm"} font-bold text-slate-900 mt-1`}>{interview.title}</p>
                                                    <p className="text-xs text-slate-500 mb-3">{interview.company} &bull; {interview.type === "video" ? "Video Call" : interview.type === "phone" ? "Phone Screen" : "In Person"}</p>
                                                    {idx === 0 && (
                                                        <div className="flex gap-2">
                                                            {interview.videoLink && (
                                                                <Button asChild size="sm" className="flex-1">
                                                                    <a href={interview.videoLink} target="_blank" rel="noopener noreferrer">Join Call</a>
                                                                </Button>
                                                            )}
                                                            <Button variant="outline" size="sm" className="flex-1">Reschedule</Button>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            ) : (
                                <div className="flex flex-col items-center justify-center py-8 text-center">
                                    <Calendar className="h-8 w-8 text-slate-300 mb-2" />
                                    <p className="text-sm font-medium text-slate-600">No upcoming interviews</p>
                                    <p className="text-xs text-slate-400 mt-1">Interviews will appear here once scheduled</p>
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    <CareerInsightsWidget />
                    <LearningResourcesWidget />
                    <SkillsAssessmentWidget />
                </div>
            </div>
        </motion.div>
    );
}

// Subcomponents

function StatCard({ title, value, icon, bg, status, action, href }: any) {
    return (
        <Card className="flex flex-col justify-between group hover:border-primary/30 hover:shadow-md transition-all">
            <CardContent className="p-5">
                <div className="flex justify-between items-start">
                    <div className={`p-2.5 rounded-xl ${bg}`}>{icon}</div>
                    <h3 className="text-3xl font-black tracking-tight text-slate-900">{value}</h3>
                </div>
                <div className="mt-4 flex items-end justify-between">
                    <div>
                        <p className="text-sm font-semibold text-slate-700">{title}</p>
                        {status && <p className="text-xs text-slate-500 mt-0.5">{status}</p>}
                    </div>
                    {action && href && (
                        <Link href={href} className="text-xs font-bold text-primary hover:underline group-hover:translate-x-1 transition-transform">
                            {action} →
                        </Link>
                    )}
                </div>
            </CardContent>
        </Card>
    );
}

function JobCard({ job, user, isSaved = false }: { job: any, user: any, isSaved?: boolean }) {
    const [saved, setSaved] = useState(isSaved);
    const [submitting, setSubmitting] = useState(false);

    const handleSave = async (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        if (submitting) return;

        setSubmitting(true);
        try {
            await toggleSaveJobAction(job.id, user?.id || "");
            setSaved(!saved);
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Card className="group flex flex-col justify-between hover:border-primary/40 hover:shadow-md transition-all">
            <CardContent className="p-5">
                <div className="flex items-start justify-between mb-3">
                    <div className="h-10 w-10 shrink-0 rounded-lg bg-slate-100 font-bold text-slate-500 flex items-center justify-center border border-slate-200">
                        {job.company.charAt(0)}
                    </div>

                    <div className="flex flex-col items-end gap-2">
                        <button
                            onClick={handleSave}
                            disabled={submitting}
                            className={`p-1.5 rounded-full transition-colors ${saved ? 'bg-primary/10 text-primary' : 'bg-slate-50 text-slate-400 hover:text-slate-600 hover:bg-slate-100'}`}
                            aria-label={saved ? "Unsave job" : "Save job"}
                        >
                            {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bookmark className="h-4 w-4" fill={saved ? "currentColor" : "none"} />}
                        </button>
                    </div>
                </div>

                <Link href={`/jobs/${job.id}`} className="block">
                    <h4 className="font-bold text-slate-900 group-hover:text-primary transition-colors line-clamp-1">{job.title}</h4>
                    <p className="text-sm text-slate-500 mt-1 flex items-center gap-1.5 line-clamp-1">
                        {job.company}
                        <span className="w-1 h-1 rounded-full bg-slate-300"></span>
                        <MapPin className="h-3.5 w-3.5" /> {job.location}
                    </p>
                </Link>

                <div className="mt-5 pt-4 border-t border-slate-100 flex items-center justify-between">
                    <div className="flex gap-2">
                        <Badge variant="secondary" className="text-[10px]">
                            {job.type}
                        </Badge>
                        {job.matchScore > 80 && (
                            <Badge className="bg-emerald-50 text-emerald-700 hover:bg-emerald-100 text-[10px]">
                                <Sparkles className="h-3 w-3 mr-1" /> {job.matchScore}% Match
                            </Badge>
                        )}
                    </div>

                    <Link
                        href={`/jobs/${job.id}/apply`}
                        className="text-sm font-bold text-primary group-hover:underline flex items-center gap-1"
                    >
                        Apply
                    </Link>
                </div>
            </CardContent>
        </Card>
    );
}
