// app/(dashboard)/job-seeker/applications/page.tsx
"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { 
  Briefcase, 
  MapPin, 
  Calendar, 
  Eye, 
  ChevronRight,
  TrendingUp,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Search,
  Download,
  Share2,
  MessageCircle,
  Calendar as CalendarIcon,
  FileText,
  ArrowUpRight,
  MoreVertical
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Badge } from "@/components/ui/Badge";

export default function ApplicationsPage() {
  const [statusFilter, setStatusFilter] = useState("all");

  const applications = [
    {
      id: 1,
      job: "Senior Frontend Developer",
      company: "WebTech Inc",
      companyLogo: "WT",
      location: "Remote",
      type: "Full-time",
      appliedDate: "Feb 15, 2024",
      status: "interview",
      nextStep: "Technical Interview on Feb 25",
      salary: "$80k - $110k",
      match: 94,
      description: "Leading the frontend development for enterprise applications using React and Next.js."
    },
    {
      id: 2,
      job: "Product Manager",
      company: "Innovate Corp",
      location: "Addis Ababa",
      type: "Full-time",
      appliedDate: "Feb 10, 2024",
      status: "reviewed",
      nextStep: "Application under review by hiring team",
      salary: "$90k - $120k",
      match: 87,
      description: "Drive product strategy and roadmap for innovative tech solutions."
    },
    {
      id: 3,
      job: "Data Analyst",
      company: "DataWorks",
      location: "Hybrid",
      type: "Contract",
      appliedDate: "Feb 8, 2024",
      status: "pending",
      nextStep: "Awaiting response from employer",
      salary: "$60k - $80k",
      match: 76,
      description: "Analyze complex datasets and provide actionable insights."
    },
    {
      id: 4,
      job: "UX Designer",
      company: "Creative Studio",
      location: "Addis Ababa",
      type: "Part-time",
      appliedDate: "Feb 5, 2024",
      status: "rejected",
      nextStep: "Application not selected for this position",
      salary: "$50k - $65k",
      match: 68,
      description: "Create beautiful and intuitive user experiences."
    }
  ];

  const getStatusConfig = (status: string) => {
    switch (status) {
      case "interview":
        return { 
          text: "Interview", 
          icon: CalendarIcon,
          colorClass: "text-emerald-600 bg-emerald-50 border-emerald-100",
          progress: 100,
          progressClass: "bg-emerald-500"
        };
      case "reviewed":
        return { 
          text: "Reviewed", 
          icon: Clock,
          colorClass: "text-amber-600 bg-amber-50 border-amber-100",
          progress: 75,
          progressClass: "bg-amber-500"
        };
      case "rejected":
        return { 
          text: "Rejected", 
          icon: XCircle,
          colorClass: "text-rose-600 bg-rose-50 border-rose-100",
          progress: 100,
          progressClass: "bg-rose-500"
        };
      default:
        return { 
          text: "Pending", 
          icon: CheckCircle,
          colorClass: "text-sky-600 bg-sky-50 border-sky-100",
          progress: 50,
          progressClass: "bg-sky-500"
        };
    }
  };

  const filteredApplications = statusFilter === "all" 
    ? applications 
    : applications.filter(app => app.status === statusFilter);

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 }
  };

  return (
    <motion.div 
      variants={containerVariants}
      initial="hidden"
      animate="visible"
      className="max-w-6xl mx-auto space-y-10"
    >
      {/* Header Section */}
      <motion.div variants={itemVariants} className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-3">
            <div className="p-2 bg-sky-100 rounded-xl">
              <Briefcase className="w-6 h-6 text-sky-600" />
            </div>
            My Applications
          </h1>
          <p className="text-slate-500 font-medium mt-1">
            Tracking <span className="text-sky-600 font-bold">{applications.length}</span> active applications and interviews.
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Button variant="outline" leftIcon={<Download className="w-4 h-4" />}>
            Export PDF
          </Button>
          <Button variant="primary" leftIcon={<FileText className="w-4 h-4" />}>
            New Application
          </Button>
        </div>
      </motion.div>

      {/* Stats Summary Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        {[
          { label: "Applied", value: "24", change: "+12%", color: "sky", icon: FileText },
          { label: "Interviews", value: "4", change: "+2", color: "emerald", icon: CalendarIcon },
          { label: "Reviewed", value: "8", change: "+3", color: "amber", icon: Clock },
          { label: "Rejected", value: "3", change: "0", color: "rose", icon: XCircle },
        ].map((stat, idx) => {
          const Icon = stat.icon;
          return (
            <motion.div key={idx} variants={itemVariants}>
              <Card variant="default" className="relative overflow-hidden group hover:shadow-2xl hover:shadow-slate-200/50 transition-all duration-500 border-slate-100/80">
                <div className={`absolute -right-4 -top-4 w-24 h-24 bg-${stat.color}-500/5 rounded-full blur-2xl group-hover:scale-150 transition-transform duration-700`} />
                <CardContent className="p-6">
                  <div className="flex items-center justify-between mb-5">
                    <div className="p-3 rounded-2xl bg-slate-50 border border-slate-100 shadow-sm transition-transform group-hover:scale-110 duration-300">
                      <Icon className={`w-6 h-6 text-${stat.color}-600`} />
                    </div>
                    <Badge variant="success" className="bg-emerald-50 text-emerald-600 border-none font-bold text-[10px] px-2 py-0.5 flex items-center gap-1">
                      <ArrowUpRight className="w-3 h-3" />
                      {stat.change}
                    </Badge>
                  </div>
                  <div>
                    <h3 className="text-3xl font-black text-slate-900 leading-none">{stat.value}</h3>
                    <p className="text-sm font-bold text-slate-500 mt-2 tracking-tight">{stat.label}</p>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          );
        })}
      </div>

      {/* Filter Bar */}
      <motion.div variants={itemVariants} className="flex flex-col sm:flex-row sm:items-center justify-between gap-6 bg-white p-4 rounded-2xl border border-slate-100 shadow-sm">
        <div className="flex flex-wrap gap-2">
          {["all", "interview", "reviewed", "pending", "rejected"].map((status) => (
            <button
              key={status}
              onClick={() => setStatusFilter(status)}
              className={`px-5 py-2 rounded-xl text-xs font-bold transition-all duration-300 ${
                statusFilter === status
                  ? "bg-sky-900 text-white shadow-lg shadow-sky-900/20"
                  : "bg-slate-100 text-slate-500 hover:bg-slate-200"
              }`}
            >
              {status.toUpperCase()}
            </button>
          ))}
        </div>
        <div className="relative group min-w-[280px]">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 group-focus-within:text-sky-600 transition-colors" />
          <input
            type="text"
            placeholder="Search company or role..."
            className="w-full pl-11 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-sky-500/20 focus:border-sky-500 transition-all"
          />
        </div>
      </motion.div>

      {/* Applications List */}
      <div className="space-y-6 min-h-[400px]">
        <AnimatePresence mode="wait">
          {filteredApplications.length > 0 ? (
            <motion.div 
              key={statusFilter}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-6"
            >
              {filteredApplications.map((app, idx) => {
                const statusConfig = getStatusConfig(app.status);
                const StatusIcon = statusConfig.icon;
                
                return (
                  <Card key={app.id} variant="default" className="overflow-hidden border-slate-100/80 hover:shadow-xl hover:shadow-slate-200/50 transition-all duration-500">
                    <CardContent className="p-0">
                      <div className="p-6 md:p-8">
                        <div className="flex flex-col lg:flex-row gap-8">
                          {/* Company Info Section */}
                          <div className="flex-1">
                            <div className="flex items-start gap-6">
                              <div className="shrink-0 w-16 h-16 rounded-2xl bg-slate-50 border border-slate-100 flex items-center justify-center text-xl font-black text-sky-600 shadow-inner">
                                {app.companyLogo || app.company.charAt(0)}
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center justify-between mb-2">
                                  <h3 className="text-xl font-extrabold text-slate-900 group-hover:text-sky-600 transition-colors truncate">
                                    {app.job}
                                  </h3>
                                  <button className="text-slate-400 hover:text-slate-600 transition-colors lg:hidden">
                                    <MoreVertical className="w-5 h-5" />
                                  </button>
                                </div>
                                <p className="text-slate-500 font-bold text-sm mb-4">{app.company}</p>
                                
                                <div className="flex flex-wrap gap-4 text-xs font-semibold">
                                  <span className="flex items-center gap-2 text-slate-400">
                                    <MapPin className="w-3.5 h-3.5" />
                                    {app.location}
                                  </span>
                                  <span className="flex items-center gap-2 text-slate-400">
                                    <Clock className="w-3.5 h-3.5" />
                                    {app.type}
                                  </span>
                                  <span className="flex items-center gap-2 text-slate-400">
                                    <Calendar className="w-3.5 h-3.5" />
                                    Applied {app.appliedDate}
                                  </span>
                                </div>

                                {/* Description Snippet */}
                                <p className="mt-5 text-sm text-slate-500 line-clamp-2 leading-relaxed">
                                  {app.description}
                                </p>
                              </div>
                            </div>
                          </div>

                          {/* Status & Actions Section */}
                          <div className="lg:w-80 shrink-0 space-y-6">
                            <div className="flex items-center justify-between lg:flex-col lg:items-end gap-4">
                              <div className={`px-4 py-1.5 rounded-full border flex items-center gap-2 shadow-sm ${statusConfig.colorClass}`}>
                                <StatusIcon className="w-3.5 h-3.5" />
                                <span className="text-xs font-black uppercase tracking-wider">{statusConfig.text}</span>
                              </div>
                              <div className="flex items-center gap-2 text-xs font-bold text-slate-400">
                                <TrendingUp className="w-3.5 h-3.5 text-emerald-500" />
                                {app.match}% Candidate Match
                              </div>
                            </div>

                            {/* Next Step Banner */}
                            <div className="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                              <p className="text-[10px] font-black text-sky-600 uppercase tracking-widest mb-1.5">Next Step</p>
                              <p className="text-xs font-bold text-slate-700 leading-relaxed">
                                {app.nextStep}
                              </p>
                            </div>

                            <div className="flex gap-3">
                              <Button variant="outline" className="flex-1" leftIcon={<MessageCircle className="w-4 h-4" />}>
                                Message
                              </Button>
                              <Button variant="primary" className="flex-1 shadow-lg shadow-sky-600/10" rightIcon={<ChevronRight className="w-4 h-4" />}>
                                Details
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* Footer Status Progress */}
                      <div className="h-1.5 w-full bg-slate-50 relative overflow-hidden">
                        <motion.div 
                          initial={{ width: 0 }}
                          animate={{ width: `${statusConfig.progress}%` }}
                          transition={{ duration: 1, ease: "easeOut", delay: 0.5 }}
                          className={`h-full ${statusConfig.progressClass} shadow-[0_0_12px_rgba(0,0,0,0.1)]`}
                        />
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </motion.div>
          ) : (
            <motion.div
              key="empty"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="text-center py-24 bg-slate-50/50 rounded-3xl border-2 border-dashed border-slate-200"
            >
              <div className="w-20 h-20 mx-auto mb-6 bg-white rounded-2xl flex items-center justify-center shadow-sm border border-slate-100">
                <Briefcase className="w-10 h-10 text-slate-300" />
              </div>
              <h3 className="text-xl font-extrabold text-slate-900 mb-2">No applications found</h3>
              <p className="text-slate-500 font-medium max-w-xs mx-auto">
                We couldn't find any applications matching your current filter.
              </p>
              <Button 
                variant="outline" 
                className="mt-8"
                onClick={() => setStatusFilter("all")}
              >
                Show all applications
              </Button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </motion.div>
  );
}