"use client";

import { FileText, Star, Eye, Check, X, Calendar, ChevronDown, Loader2 } from "lucide-react";
import Image from "next/image";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth.store";
import { useAppliedJobs, useAppliedJobsStats } from "@/hooks/useJobs";
import { format } from "date-fns";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import Link from "next/link";
import { generateJobUrl } from "@/utils/generateJobUrl";

const getLogoUrl = (logo: string | undefined) => {
  if (typeof logo !== 'string' || !logo.trim() || logo === 'null' || logo === 'undefined') return null;
  if (!logo.startsWith('http') && !logo.startsWith('/')) {
    return `/${logo}`;
  }
  return logo;
};

export default function SeekerApplicationsPage() {
  const router = useRouter();
  const { user, isAuthenticated } = useAuthStore();
  const [mounted, setMounted] = useState(false);
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<string | undefined>(undefined);

  useEffect(() => {
    setMounted(true);
  }, []);

  const { data: statsRes, isLoading: isStatsLoading } = useAppliedJobsStats(user?.id);
  const { data: jobsRes, isLoading: isJobsLoading } = useAppliedJobs(user?.id, page, 10, statusFilter);

  // Default stats values
  const stats = statsRes?.success ? statsRes.data : {
    total: 0, shortlisted: 0, interview: 0, hired: 0, rejected: 0, expired: 0
  };

  const applications = jobsRes?.success ? jobsRes.data.applications : [];
  const pagination = jobsRes?.success ? jobsRes.data.pagination : { page: 1, totalPages: 1 };

  const applicationStats = [
    {
      id: undefined,
      title: "All Applications",
      count: stats.total,
      icon: <FileText className="w-5 h-5 text-purple-600 fill-current" />,
      iconBg: "bg-purple-100",
      activeColor: "border-purple-600"
    },
    {
      id: "shortlisted",
      title: "Shortlisted",
      count: stats.shortlisted,
      icon: <Star className="w-5 h-5 text-pink-500" />,
      iconBg: "bg-pink-100",
      activeColor: "border-pink-500"
    },
    {
      id: "interview",
      title: "Interview",
      count: stats.interview,
      icon: <Eye className="w-5 h-5 text-blue-500" />,
      iconBg: "bg-blue-100",
      activeColor: "border-blue-500"
    },
    {
      id: "hired",
      title: "Offered",
      count: stats.hired,
      icon: <Check className="w-5 h-5 text-green-500 stroke-[3]" />,
      iconBg: "bg-green-100",
      activeColor: "border-green-500"
    },
    {
      id: "rejected",
      title: "Rejected",
      count: stats.rejected,
      icon: <X className="w-5 h-5 text-red-500 stroke-[3]" />,
      iconBg: "bg-red-100",
      activeColor: "border-red-500"
    },
    {
      id: "expired",
      title: "Expired",
      count: stats.expired,
      icon: <Calendar className="w-5 h-5 text-orange-500" />,
      iconBg: "bg-orange-100",
      activeColor: "border-orange-500"
    },
  ];

  const getStatusStyles = (status: string) => {
    const s = status?.toLowerCase() || '';
    if (s === 'hired' || s === 'offered') return "bg-[#dcfce7] text-green-700";
    if (s === 'interview') return "bg-blue-100 text-blue-600";
    if (s === 'shortlisted') return "bg-pink-100 text-pink-600";
    if (s === 'rejected') return "bg-red-100 text-red-600";
    if (s === 'applied') return "bg-blue-100 text-blue-600";
    return "bg-gray-100 text-gray-700";
  };

  const getInitials = (name: string) => name ? name.substring(0, 2).toUpperCase() : "NA";

  if (!mounted) return null;

  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh] text-center p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-2">Please Login</h3>
        <p className="text-sm text-gray-500 mb-6">You need to be logged in to view your applications.</p>
        <button onClick={() => router.push('/?login=true')} className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-2.5 rounded-md text-sm font-semibold transition-colors">
          Login Now
        </button>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6 lg:p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Applications</h1>
          <p className="text-sm text-gray-600 mt-1">Track your job applications and their status</p>
        </div>
        <Link href="/" className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-6 py-2.5 rounded-lg text-sm font-semibold transition-colors flex items-center gap-2 shadow-sm">
          + Add Application
        </Link>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-10">
        {applicationStats.map((stat, idx) => {
          const isActive = statusFilter === stat.id;
          return (
            <button
              key={idx}
              onClick={() => {
                setStatusFilter(stat.id);
                setPage(1);
              }}
              className={`bg-white rounded-xl p-5 flex flex-col items-center justify-center text-center shadow-sm relative transition-colors ${isActive ? 'border-b-4 ' + stat.activeColor : 'border border-gray-100 hover:border-gray-200'}`}
            >
              <div className={`w-12 h-12 rounded-xl ${stat.iconBg} flex items-center justify-center mb-3`}>
                {stat.icon}
              </div>
              <div className="text-xl font-bold text-gray-900 mb-1">
                {isStatsLoading ? <Loader2 className="w-5 h-5 animate-spin text-gray-400" /> : stat.count}
              </div>
              <div className="text-xs text-gray-500 font-medium">{stat.title}</div>
            </button>
          )
        })}
      </div>

      {isJobsLoading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-[#ff6b00]" />
        </div>
      ) : applications.length > 0 ? (
        <>
          {/* Recent Activity Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-lg font-bold text-gray-900">Recent Activity</h2>
          </div>

          {/* List */}
          <div className="flex flex-col gap-4 mb-8">
            {applications.map((app: any) => {
              const jobUrl = generateJobUrl({ id: app.job_post_id, title: app.job_title } as any);
              
              return (
                <div key={app.id} className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                  {/* Left side info */}
                  <div className="flex items-center gap-5 w-full sm:w-auto">
                    {/* Logo */}
                    <div className="w-12 h-12 rounded-full relative bg-gray-100 border border-gray-100 flex items-center justify-center overflow-hidden flex-shrink-0">
                      {getLogoUrl(app.company_logo) ? (
                        <Image src={getLogoUrl(app.company_logo)!} alt={app.company_name} fill className="object-cover" />
                      ) : (
                        <span className="text-[#ff6b00] font-bold text-lg">{getInitials(app.company_name)}</span>
                      )}
                    </div>

                    {/* Text */}
                    <div className="flex-1">
                      <h3 className="text-[15px] font-bold text-gray-900 mb-1 hover:text-[#ff6b00] transition-colors">
                        <Link href={jobUrl}>
                          {app.job_title}
                        </Link>
                      </h3>
                      <p className="text-xs text-gray-500 mb-2">{app.company_name}</p>
                      <div className="flex flex-wrap items-center gap-4 text-[11px] text-gray-500 font-medium">
                        <div className="flex items-center gap-1.5">
                          <Calendar className="w-3.5 h-3.5" /> Applied on: {app.applied_at ? format(new Date(app.applied_at), 'MMM dd, yyyy') : 'N/A'}
                        </div>
                        <div className="flex items-center gap-1.5">
                          <Calendar className="w-3.5 h-3.5" /> Expires on: {app.expires_at ? format(new Date(app.expires_at), 'MMM dd, yyyy') : 'N/A'}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Right side actions */}
                  <div className="flex flex-col items-end gap-3 w-full sm:w-auto">
                    <div className={`px-4 py-1 rounded-full text-[11px] font-bold capitalize ${getStatusStyles(app.application_status)} self-end sm:self-auto`}>
                      {app.application_status || 'Applied'}
                    </div>
                    <div className="flex items-center gap-3 text-xs font-semibold">
                      <Link href={jobUrl} className="text-[#ff6b00] hover:underline">
                        View details
                      </Link>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Pagination */}
          {pagination.totalPages > 1 && (
            <div className="flex items-center justify-end gap-2 text-sm mt-8">
              <button 
                onClick={() => setPage(p => Math.max(1, p - 1))}
                disabled={page === 1}
                className="px-3 py-1 text-gray-400 hover:text-gray-700 disabled:opacity-50 transition-colors"
              >
                Prev
              </button>
              
              {Array.from({ length: pagination.totalPages }, (_, i) => i + 1).map((p) => (
                <button 
                  key={p}
                  onClick={() => setPage(p)}
                  className={`w-8 h-8 flex items-center justify-center rounded border transition-colors ${
                    page === p 
                      ? 'border-[#ff6b00] text-[#ff6b00] font-medium bg-orange-50' 
                      : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {p}
                </button>
              ))}

              <button 
                onClick={() => setPage(p => Math.min(pagination.totalPages, p + 1))}
                disabled={page === pagination.totalPages}
                className="px-3 py-1 font-semibold text-gray-800 hover:text-black disabled:opacity-50 transition-colors"
              >
                Next
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="flex flex-col items-center justify-center mt-6 lg:mt-12 mb-16 text-center">
          <div className="relative w-56 h-56 sm:w-64 sm:h-64 mb-6">
            <Image
              src="/images/noApply.png"
              alt="No applications yet"
              fill
              className="object-contain"
            />
          </div>
          <h3 className="text-xl font-bold text-gray-900 mb-2">No applications found</h3>
          <p className="text-sm text-gray-500 max-w-sm mb-6 leading-relaxed">
            {statusFilter 
              ? `You don't have any applications with the status "${applicationStats.find(s => s.id === statusFilter)?.title}".` 
              : "You haven't applied to any jobs yet. Start exploring opportunities and track all your applications in one place."}
          </p>
          <Link href="/" className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-2.5 rounded-md text-sm font-semibold transition-colors shadow-sm">
            Explore Jobs
          </Link>
        </div>
      )}

    </div>
  );
}
