import { ArrowLeft, Briefcase, Clock, MapPin, Building2, User, Share2 } from "lucide-react";
import Link from "next/link";
import { DownloadAppCard } from "@/components/seeker/dashboard/DownloadAppCard";
import { DirectoryLinks } from "@/components/DirectoryLinks";
import { JobActions } from "@/components/jobs/JobActions";
import { JobService } from "@/services/job.service";
import { formatIndianSalaryRange } from "@/utils/formatIndianSalary";
import { Metadata } from "next";
import { notFound } from "next/navigation";

interface JobDetailPageProps {
  params: Promise<{ slug: string }>;
}

export async function generateMetadata({ params }: JobDetailPageProps): Promise<Metadata> {
  try {
    const { slug } = await params;
    const parts = slug.split("-");
    const id = parts[parts.length - 1];
    
    const job = await JobService.getJobDetails(id);
    if (!job) return { title: "Job Not Found" };

    return {
      title: `${job.title} at ${job.company?.company_name} - JobVumi`,
      description: job.description?.substring(0, 160),
    };
  } catch (error) {
    return { title: "Job Not Found" };
  }
}

export default async function JobDetailPage({ params }: JobDetailPageProps) {
  let job;
  try {
    const { slug } = await params;
    const parts = slug.split("-");
    const id = parts[parts.length - 1];

    job = await JobService.getJobDetails(id);
  } catch (error) {
    console.error("Error fetching job details:", error);
    notFound();
  }

  if (!job) {
    notFound();
  }

  return (
    <div className="bg-[#fcfdfd] min-h-screen pb-0 font-sans">
      
      {/* Top Header section */}
      <div className="bg-[#fcfdfd] py-5 px-4 lg:px-8 border-b border-gray-100 mb-6">
         <div className="container mx-auto max-w-7xl">
            <Link href="/jobs" className="inline-flex items-center gap-2 text-gray-900 font-bold hover:text-[#ff6b00] transition-colors text-[15px]">
              <ArrowLeft className="w-5 h-5" strokeWidth={2.5} />
              Back
            </Link>
         </div>
      </div>

      <div className="container mx-auto max-w-7xl px-4 lg:px-8 mb-12">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
           
           {/* LEFT COLUMN: Main Content */}
           <div className="lg:col-span-8 flex flex-col gap-5">
              
              {/* Job Header Card */}
              <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm relative">
                
                <div className="flex items-start gap-4 mb-5">
                  <div className="w-[52px] h-[52px] flex-shrink-0 bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden border border-gray-100 p-1">
                    {job.company?.logo_url ? (
                      <img src={job.company.logo_url} alt={job.company.company_name} className="w-full h-full object-contain" />
                    ) : (
                      <Building2 className="w-6 h-6 text-gray-400" />
                    )}
                  </div>
                  <div>
                    <h1 className="text-[19px] font-bold text-gray-900 leading-tight">{job.title}</h1>
                    <p className="text-[13px] text-gray-500 mt-0.5">{job.company?.company_name}</p>
                  </div>
                </div>

                <div className="flex flex-col gap-3 mb-5">
                  <div className="flex flex-wrap items-center gap-4 text-[13px] text-gray-600 font-medium">
                    <div className="flex items-center gap-1.5">
                      <Briefcase className="w-4 h-4 text-gray-400" />
                      <span>{job.experience || "Entry Level"}</span>
                    </div>
                    <span className="text-gray-300 hidden sm:block">|</span>
                    <div className="flex items-center gap-1.5">
                      <Clock className="w-4 h-4 text-gray-400" />
                      <span>{job.job_type || "Full Time"}</span>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-1.5 text-[13px] text-gray-600 font-medium">
                    <MapPin className="w-4 h-4 text-gray-400 flex-shrink-0" />
                    <span>{[job.city, job.state, job.country].filter(Boolean).join(', ') || "Location not specified"}</span>
                  </div>

                  <div className="flex items-center gap-1.5 text-[14px] font-bold text-gray-800 mt-1">
                    <span>{formatIndianSalaryRange(job.salary_min || 0, job.salary_max || 0)}</span>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2 mb-6">
                  {job.skills?.map((skill: any, index: number) => (
                    <span key={`${skill.id || skill.skill_name || 'skill'}-${index}`} className="px-3 py-1.5 bg-green-50 text-green-600 rounded-md text-[10px] font-bold uppercase tracking-wide">
                      {skill.skill_name}
                    </span>
                  ))}
                </div>

                <div className="flex flex-col sm:flex-row items-center justify-between pt-5 border-t border-gray-100 gap-4">
                  <div className="flex items-center gap-2 text-[13px] text-gray-500 font-medium w-full sm:w-auto">
                    <Clock className="w-4 h-4" />
                    <span>Posted {new Date(job.created_at).toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })}</span>
                  </div>
                  
                  <div className="flex items-center gap-3 w-full sm:w-auto">
                    <JobActions jobId={job.id} isApplied={job.has_applied} isSaved={job.has_saved} />
                  </div>
                </div>
              </div>

              {/* Job Description */}
              <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm overflow-hidden">
                <h2 className="text-base font-bold text-gray-900 mb-3">Job Description</h2>
                <div 
                  className="text-[13px] text-gray-600 leading-relaxed space-y-3 whitespace-pre-wrap break-words"
                  dangerouslySetInnerHTML={{ __html: job.description || "No description provided." }}
                />
              </div>

              {/* Job Role */}
              <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
                <h2 className="text-base font-bold text-gray-900 mb-5">Job Role</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-6 gap-x-4">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-lg bg-orange-50 flex items-center justify-center flex-shrink-0 text-[#ff6b00]">
                      <Building2 className="w-5 h-5" />
                    </div>
                    <div>
                      <p className="text-[11px] text-gray-400 font-medium">Industry</p>
                      <p className="text-[13px] font-bold text-gray-900 mt-0.5">{job.industry || "N/A"}</p>
                    </div>
                  </div>
                  
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-lg bg-orange-50 flex items-center justify-center flex-shrink-0 text-[#ff6b00]">
                      <Briefcase className="w-5 h-5" />
                    </div>
                    <div>
                      <p className="text-[11px] text-gray-400 font-medium">Role/Category</p>
                      <p className="text-[13px] font-bold text-gray-900 mt-0.5">{job.role_name || job.role_level || "N/A"}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* About Company & Job Posted By combined card */}
              <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
                <h2 className="text-base font-bold text-gray-900 mb-4">About Company</h2>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-[42px] h-[42px] flex-shrink-0 bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden border border-gray-100 p-1">
                      {job.company?.logo_url ? (
                        <img src={job.company.logo_url} alt={job.company.company_name} className="w-full h-full object-contain" />
                      ) : (
                        <Building2 className="w-5 h-5 text-gray-400" />
                      )}
                    </div>
                    <div>
                      <h3 className="text-[13px] font-bold text-gray-900">{job.company?.company_name}</h3>
                      <div className="flex items-center gap-1 mt-0.5 text-[11px] text-gray-500 font-medium">
                        <MapPin className="w-3 h-3 text-red-500" />
                        <span>{job.company?.address || "Location not provided"}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

           </div>

           {/* RIGHT COLUMN: Sidebar Content */}
           <div className="lg:col-span-4 flex flex-col gap-5">
              
              {/* Promo App Card */}
              <div className="h-[340px]">
                <DownloadAppCard />
              </div>

           </div>

        </div>
      </div>
      
      {/* Directory Links Footer Section */}
      <div className="bg-white border-t border-gray-100">
        <DirectoryLinks />
      </div>

    </div>
  );
}
