"use client";

import { WelcomeBanner } from "@/components/seeker/dashboard/WelcomeBanner";
import { ProfileCompletionCard } from "@/components/seeker/dashboard/ProfileCompletionCard";
import { StatCard } from "@/components/seeker/dashboard/StatCard";
import { JobCard, DashboardJob } from "@/components/seeker/dashboard/JobCard";
import { DownloadAppCard } from "@/components/seeker/dashboard/DownloadAppCard";
import { RecentApplications, DashboardApplication } from "@/components/seeker/dashboard/RecentApplications";
import { UpcomingInterviews, DashboardInterview } from "@/components/seeker/dashboard/UpcomingInterviews";
import { FileText, Heart, Bell, Calendar } from "lucide-react";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { format } from "date-fns";
import Link from "next/link";

export default function SeekerDashboardPage() {
  const { user, isLoading: isUserLoading } = useCurrentUser();
  const userId = user?.id;
  const seekerId = user?.seekerProfile?.id; // Assuming nested profile, or we fallback if not

  // Fetch Overview Stats
  const { data: overviewRes, isLoading: isOverviewLoading } = useQuery({
    queryKey: ['seekerOverview', userId],
    queryFn: async () => {
      const res = await api.get(`/dashboard/seeker/overview`, { params: { userId } });
      return res.data;
    },
    enabled: !!userId,
  });

  // Fetch Profile Completion
  const { data: completionRes } = useQuery({
    queryKey: ['seekerProfileCompletion', userId],
    queryFn: async () => {
      const res = await api.get(`/dashboard/seeker/profile_completion`, { params: { userId } });
      return res.data;
    },
    enabled: !!userId,
  });

  // Fetch Jobs based on Profile (from mobile dashboard)
  const { data: jobsRes, isLoading: isJobsLoading } = useQuery({
    queryKey: ['seekerJobsBasedOnProfile', userId],
    queryFn: async () => {
      const res = await api.get(`/mobile/dashboard`, { params: { userId, limit: 100 } });
      return res.data;
    },
    enabled: !!userId,
  });

  // Fetch Upcoming Interviews
  const { data: interviewsRes } = useQuery({
    queryKey: ['seekerUpcomingInterviews', seekerId || userId],
    queryFn: async () => {
      const res = await api.get(`/ai_interview_schedules/seeker/${seekerId || userId}`);
      return res.data;
    },
    enabled: !!(seekerId || userId),
  });

  if (isUserLoading) {
    return <div className="p-8 text-center text-gray-500">Loading your dashboard...</div>;
  }

  // Extract data from responses
  const overview = overviewRes?.data || overviewRes || {};
  const completionPercent = completionRes?.data?.percentage || completionRes?.percentage || 0;
  
  const recommendedJobs: DashboardJob[] = jobsRes?.jobs_based_on_profile?.map((job: any) => ({
    id: job.job_id || job.id,
    title: job.title || job.job_title,
    company_name: job.company_name || job.company_details?.name || 'Unknown Company',
    company_logo: job.company_logo || job.company_logo_url,
    location: job.location || job.full_company_address || (job.city_name ? `${job.city_name}, ${job.state_name || ''}`.replace(/,\s*$/, '') : 'Not specified'),
    job_type: job.employment_type || job.job_type_name || job.role?.employment_type || 'Full Time',
    min_salary: job.salary_min || job.min_salary,
    max_salary: job.salary_max || job.max_salary,
    skills: job.skills || (job.requirements?.skills ? job.requirements.skills.split(', ').map((s: string) => s.trim()) : []),
    created_at: job.posted_date || job.created_at || job.created_on || new Date().toISOString(),
    is_saved: job.is_saved,
    has_saved: job.has_saved
  })) || [];
  const upcomingInterviews: DashboardInterview[] = interviewsRes?.data || interviewsRes || [];
  const recentApplications: DashboardApplication[] = overview.recentApplications || [];

  // Derived stats
  const totalApplied = overview.totalApplied || 0;
  const monthlyApplied = overview.monthlyApplied || 0;
  
  const totalFavorites = overview.totalFavorites || 0;
  const monthlyFavorites = overview.monthlyFavorites || 0;
  
  const totalAlerts = overview.totalAlerts || 0;
  const monthlyAlerts = overview.monthlyAlerts || 0;

  // Placeholder for interview stats if not provided by overview
  const totalInterviews = upcomingInterviews.length;
  const monthlyInterviews = upcomingInterviews.filter(i => {
    const d = new Date(i.interview_date);
    const now = new Date();
    return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
  }).length;

  const userName = user ? user.full_name || user.fullName || `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username : 'Seeker';
  const userTitle = user?.seekerProfile?.current_job_title || user?.seekerProfile?.headline || "Update your profile";
  const userAvatar = user?.seekerProfile?.profile_picture;
  const currentDate = format(new Date(), "EEEE, MMMM d, yyyy");

  return (
    <div className="p-4 sm:p-6 lg:p-8">
      {/* Top & Middle Section */}
      <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 mb-6">
        
        {/* Left/Main Column */}
        <div className="xl:col-span-9 flex flex-col gap-6">
          
          {/* Top Header Row */}
          <div className="flex justify-between items-start">
            <div>
              <h1 className="text-xl sm:text-2xl font-bold text-gray-900 flex items-center gap-2">
                Good morning, {userName} <span className="text-xl sm:text-2xl">👋</span>
              </h1>
              <p className="text-xs sm:text-sm text-gray-600 mt-1">
                Your career journey is looking promising today.
              </p>
            </div>
            <div className="hidden md:flex items-center gap-2 bg-white px-4 py-2.5 rounded-lg border border-gray-100 shadow-sm">
              <Calendar className="w-4 h-4 text-gray-500" />
              <span className="text-sm font-medium text-gray-700">{currentDate}</span>
            </div>
          </div>

          <WelcomeBanner />

          {/* Stats Row */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <StatCard 
              title="Applications" 
              value={totalApplied.toString()} 
              increase={`${monthlyApplied} This Month`} 
              icon={<FileText className="w-5 h-5" />} 
              iconBgColor="bg-purple-100" 
              iconTextColor="text-purple-600" 
            />
            <StatCard 
              title="Saved Jobs" 
              value={totalFavorites.toString()} 
              increase={`${monthlyFavorites} This Month`} 
              icon={<Heart className="w-5 h-5 fill-current" />} 
              iconBgColor="bg-pink-100" 
              iconTextColor="text-pink-500" 
            />
            <StatCard 
              title="Job Alerts" 
              value={totalAlerts.toString()} 
              increase={`${monthlyAlerts} This Month`} 
              icon={<Bell className="w-5 h-5 fill-current" />} 
              iconBgColor="bg-blue-100" 
              iconTextColor="text-blue-500" 
            />
            <StatCard 
              title="Interviews" 
              value={totalInterviews.toString()} 
              increase={`${monthlyInterviews} This Month`} 
              icon={<Calendar className="w-5 h-5" />} 
              iconBgColor="bg-green-100" 
              iconTextColor="text-green-600" 
            />
          </div>

          {/* Jobs based on Your Profile */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 flex flex-col">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-900 text-lg">Jobs based on Your Profile</h3>
              <Link href="/jobs?type=profile" className="text-sm font-medium text-[#ff6b00] hover:underline">View All</Link>
            </div>
            
            {isJobsLoading ? (
              <div className="py-10 text-center text-gray-500">Loading recommendations...</div>
            ) : recommendedJobs.length === 0 ? (
              <div className="py-10 text-center text-gray-500">No jobs recommended at the moment. Complete your profile to get better matches!</div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {recommendedJobs.slice(0, 3).map((job, idx) => (
                  <JobCard key={job.id || idx} job={job} />
                ))}
              </div>
            )}

          </div>
        </div>

        {/* Right Column */}
        <div className="hidden md:flex xl:col-span-3 flex-col gap-6">
          <ProfileCompletionCard 
            percentage={completionPercent} 
            name={userName} 
            title={userTitle}
            avatarUrl={userAvatar}
            missingFields={completionRes?.data?.missingFields || completionRes?.missingFields || []}
          />
          <div className="flex-1">
            <DownloadAppCard />
          </div>
        </div>
      </div>

      {/* Bottom Section: Recent Apps & Upcoming Interviews */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <RecentApplications applications={recentApplications} />
        <UpcomingInterviews interviews={upcomingInterviews} />
      </div>
    </div>
  );
}
