import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { db } from "@/lib/db";
import { readJobSlidesConfig } from "@/lib/jobs-admin-config";
import {
  Briefcase, MapPin, Clock, Building2, ArrowRight, Lock,
  Code2, BarChart3, Megaphone, Stethoscope, GraduationCap,
  Wrench, ShieldCheck, Palette, Star, Users, Zap, CheckCircle2,
} from "lucide-react";
import JobsSlider from "@/components/jobs/JobsSlider";

export const metadata: Metadata = { title: "Jobs Portal – KC Systems" };

const featuredJobs = [
  {
    id: 1, title: "Senior Software Engineer", company: "Grab", location: "Kuala Lumpur", type: "Full-time",
    salary: "$8,000–12,000", posted: "2 days ago", tags: ["React", "Node.js", "AWS"],
    image: "https://images.unsplash.com/photo-1549421263-5ec394a5ad4c?w=80&q=80", urgent: true,
  },
  {
    id: 2, title: "Product Manager", company: "AirAsia Digital", location: "Petaling Jaya", type: "Full-time",
    salary: "$7,000–10,000", posted: "3 days ago", tags: ["Product", "Agile", "Data"],
    image: "https://images.unsplash.com/photo-1516876437184-593fda40c7ce?w=80&q=80", urgent: false,
  },
  {
    id: 3, title: "UI/UX Designer", company: "Axiata Digital", location: "KL Sentral", type: "Full-time",
    salary: "$5,000–7,000", posted: "1 day ago", tags: ["Figma", "Design Systems"],
    image: "https://images.unsplash.com/photo-1611532736597-de2d4265fba3?w=80&q=80", urgent: true,
  },
  {
    id: 4, title: "Data Analyst", company: "CIMB Bank", location: "Kuala Lumpur", type: "Full-time",
    salary: "$4,500–6,500", posted: "4 days ago", tags: ["SQL", "Python", "Tableau"],
    image: "https://images.unsplash.com/photo-1554151228-14d9def656e4?w=80&q=80", urgent: false,
  },
  {
    id: 5, title: "DevOps Engineer", company: "Telekom Malaysia", location: "Remote", type: "Remote",
    salary: "$7,000–9,500", posted: "1 week ago", tags: ["Kubernetes", "CI/CD", "Linux"],
    image: "https://images.unsplash.com/photo-1560250097-0b93528c311a?w=80&q=80", urgent: false,
  },
  {
    id: 6, title: "Marketing Executive", company: "Shopee Malaysia", location: "Bangsar South", type: "Hybrid",
    salary: "$3,500–5,000", posted: "5 days ago", tags: ["Digital Marketing", "SEO"],
    image: "https://images.unsplash.com/photo-1573497019940-1c28c88b4f3e?w=80&q=80", urgent: false,
  },
];

const recentJobs = [
  { id: 7, title: "Business Analyst", company: "Maybank", location: "KL", type: "Full-time", salary: "$5,000–7,000", posted: "6h ago", tags: ["Business", "Excel", "JIRA"] },
  { id: 8, title: "Cloud Architect", company: "Microsoft Malaysia", location: "Remote", type: "Remote", salary: "$12,000–18,000", posted: "8h ago", tags: ["Azure", "Cloud", "Architecture"] },
  { id: 9, title: "HR Executive", company: "Petronas", location: "KLCC", type: "Full-time", salary: "$3,800–5,200", posted: "12h ago", tags: ["HR", "Recruitment", "HRIS"] },
  { id: 10, title: "Cybersecurity Analyst", company: "MDEC", location: "Cyberjaya", type: "Full-time", salary: "$6,000–9,000", posted: "1 day ago", tags: ["Security", "SIEM", "SOC"] },
  { id: 11, title: "Content Writer", company: "iPrice Group", location: "Remote", type: "Remote", salary: "$2,800–4,000", posted: "1 day ago", tags: ["SEO", "Copywriting"] },
  { id: 12, title: "Finance Manager", company: "Maxis", location: "Kuala Lumpur", type: "Full-time", salary: "$8,000–11,000", posted: "2 days ago", tags: ["Finance", "Audit", "IFRS"] },
];

const categories = [
  { label: "Technology", icon: Code2, count: 842, color: "bg-blue-50 text-blue-600 border-blue-100", href: "/jobs?cat=tech" },
  { label: "Data & Analytics", icon: BarChart3, count: 314, color: "bg-violet-50 text-violet-600 border-violet-100", href: "/jobs?cat=data" },
  { label: "Marketing", icon: Megaphone, count: 197, color: "bg-pink-50 text-pink-600 border-pink-100", href: "/jobs?cat=marketing" },
  { label: "Healthcare", icon: Stethoscope, count: 265, color: "bg-emerald-50 text-emerald-600 border-emerald-100", href: "/jobs?cat=healthcare" },
  { label: "Education", icon: GraduationCap, count: 183, color: "bg-amber-50 text-amber-600 border-amber-100", href: "/jobs?cat=education" },
  { label: "Engineering", icon: Wrench, count: 421, color: "bg-orange-50 text-orange-600 border-orange-100", href: "/jobs?cat=engineering" },
  { label: "Security", icon: ShieldCheck, count: 128, color: "bg-red-50 text-red-600 border-red-100", href: "/jobs?cat=security" },
  { label: "Design & Creative", icon: Palette, count: 156, color: "bg-teal-50 text-teal-600 border-teal-100", href: "/jobs?cat=design" },
];

const typeColors: Record<string, string> = {
  "Full-time": "bg-blue-50 text-blue-700",
  "Remote": "bg-emerald-50 text-emerald-700",
  "Hybrid": "bg-purple-50 text-purple-700",
  "Part-time": "bg-amber-50 text-amber-700",
  "Contract": "bg-orange-50 text-orange-700",
  "Internship": "bg-teal-50 text-teal-700",
};

type UiJob = {
  id: string;
  title: string;
  company: string;
  location: string;
  type: string;
  salary: string;
  posted: string;
  tags: string[];
  image: string;
  urgent: boolean;
};

function timeAgo(input: Date | null | undefined): string {
  if (!input) return "Recently";
  const diffMs = Date.now() - input.getTime();
  const hours = Math.floor(diffMs / (1000 * 60 * 60));
  if (hours < 1) return "Just now";
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days} day${days > 1 ? "s" : ""} ago`;
  const weeks = Math.floor(days / 7);
  return `${weeks} week${weeks > 1 ? "s" : ""} ago`;
}

function mapJobToUi(job: {
  id: string;
  title: string;
  company: string | null;
  location: string | null;
  jobType: string | null;
  salary: string | null;
  postedAt: Date | null;
}): UiJob {
  return {
    id: job.id,
    title: job.title,
    company: job.company || "Confidential",
    location: job.location || "Malaysia",
    type: job.jobType || "Full-time",
    salary: job.salary || "Negotiable",
    posted: timeAgo(job.postedAt),
    tags: [job.jobType || "Role", "Career", "Malaysia"],
    image: "https://images.unsplash.com/photo-1549421263-5ec394a5ad4c?w=80&q=80",
    urgent: false,
  };
}

export default async function JobsPage() {
  const [dbJobs, sliderRows] = await Promise.all([
    db.job.findMany({
      where: { isActive: true },
      orderBy: [{ postedAt: "desc" }, { createdAt: "desc" }],
      take: 18,
      select: {
        id: true,
        title: true,
        company: true,
        location: true,
        jobType: true,
        salary: true,
        postedAt: true,
        isFeatured: true,
      },
    }),
    readJobSlidesConfig(),
  ]);

  const sliderData = sliderRows
    .filter((s) => s.isActive)
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((s) => ({
      id: s.id,
      label: s.label,
      title: s.title,
      subtitle: s.subtitle,
      image: s.imageUrl,
    }));

  const featuredJobsData: UiJob[] = dbJobs.some((j) => j.isFeatured)
    ? dbJobs.filter((j) => j.isFeatured).slice(0, 6).map(mapJobToUi)
    : featuredJobs.map((j) => ({ ...j, id: String(j.id) }));

  const recentJobsData: UiJob[] = dbJobs.length > 0
    ? dbJobs.slice(0, 6).map(mapJobToUi)
    : recentJobs.map((j) => ({
        ...j,
        id: String(j.id),
        image: "https://images.unsplash.com/photo-1549421263-5ec394a5ad4c?w=80&q=80",
        urgent: false,
      }));

  return (
    <div className="min-h-screen bg-neutral-50">

      {/* Slider */}
      <JobsSlider slides={sliderData} />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-20 pt-14 pb-24">

        {/* Stats row */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { label: "Live Jobs", value: "2,400+", icon: Briefcase },
            { label: "Companies Hiring", value: "380+", icon: Building2 },
            { label: "Placements This Month", value: "142", icon: CheckCircle2 },
            { label: "Active Job Seekers", value: "18K+", icon: Users },
          ].map(({ label, value, icon: Icon }) => (
            <div key={label} className="bg-white border border-neutral-200 rounded-2xl p-5 flex items-center gap-4">
              <div className="w-10 h-10 bg-navy-50 rounded-xl flex items-center justify-center shrink-0">
                <Icon size={18} className="text-navy-600" />
              </div>
              <div>
                <div className="text-xl font-bold text-navy-900">{value}</div>
                <div className="text-xs text-neutral-500">{label}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Featured Jobs */}
        <section>
          <div className="flex items-center justify-between mb-7">
            <div>
              <div className="inline-flex items-center gap-2 px-3 py-1 bg-navy-50 text-navy-700 text-xs font-semibold rounded-full mb-2 border border-navy-100">
                <Star size={11} /> Featured
              </div>
              <h2 className="text-2xl font-bold text-navy-900">Featured Jobs</h2>
              <p className="text-neutral-500 text-sm mt-0.5">Hand-picked top opportunities from leading companies</p>
            </div>
            <Link href="/jobs" className="text-sm text-navy-700 hover:text-navy-900 font-medium flex items-center gap-1">
              All jobs <ArrowRight size={14} />
            </Link>
          </div>

          {/* Subscription banner */}
          <div className="bg-gold-50 border border-gold-200 rounded-xl p-4 flex items-center justify-between gap-4 mb-6">
            <div className="flex items-center gap-3 text-sm">
              <Lock size={15} className="text-gold-600 shrink-0" />
              <span className="text-neutral-700"><strong>Subscribe to apply.</strong> Job Seeker plan from $49/month — apply directly, track applications, get alerts.</span>
            </div>
            <Link href="/register?plan=job_seeker" className="shrink-0 px-4 py-1.5 bg-gold-500 text-white text-sm font-semibold rounded-lg hover:bg-gold-600 transition-colors whitespace-nowrap">
              Subscribe Now
            </Link>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
            {featuredJobsData.map((job) => (
              <Link
                key={job.id}
                href={`/jobs/${job.id}`}
                className="group bg-white border border-neutral-200 rounded-2xl p-5 hover:shadow-lg hover:border-navy-200 transition-all flex flex-col"
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className="relative w-12 h-12 rounded-xl overflow-hidden border border-neutral-100 bg-neutral-50 shrink-0">
                      <Image src={job.image} alt={job.company} fill className="object-cover" sizes="48px" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-navy-800 text-sm leading-snug group-hover:text-navy-600 line-clamp-1">{job.title}</h3>
                      <p className="text-xs text-neutral-500 mt-0.5">{job.company}</p>
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-1.5 shrink-0">
                    <span className={`text-xs font-medium px-2.5 py-0.5 rounded-full ${typeColors[job.type] ?? "bg-neutral-100 text-neutral-600"}`}>{job.type}</span>
                    {job.urgent && <span className="text-xs font-semibold text-red-600 bg-red-50 px-2 py-0.5 rounded-full flex items-center gap-1"><Zap size={9} /> Urgent</span>}
                  </div>
                </div>

                <div className="flex flex-wrap gap-1.5 mb-4">
                  {job.tags.map((tag) => (
                    <span key={tag} className="text-xs bg-neutral-100 text-neutral-600 px-2.5 py-1 rounded-full">{tag}</span>
                  ))}
                </div>

                <div className="mt-auto pt-3 border-t border-neutral-100 flex items-center justify-between text-xs text-neutral-500">
                  <span className="flex items-center gap-1"><MapPin size={11} /> {job.location}</span>
                  <span className="flex items-center gap-1"><Clock size={11} /> {job.posted}</span>
                  <span className="font-semibold text-emerald-600">{job.salary}</span>
                </div>
              </Link>
            ))}
          </div>
        </section>

        {/* CTA — Subscribe banner */}
        <section className="relative overflow-hidden rounded-3xl">
          <div className="absolute inset-0">
            <Image
              src="https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=1400&q=80"
              alt="Team working"
              fill
              className="object-cover"
              sizes="100vw"
            />
            <div className="absolute inset-0 bg-gradient-to-r from-navy-900/95 via-navy-900/80 to-navy-900/40" />
          </div>
          <div className="relative z-10 grid md:grid-cols-2 gap-0">
            <div className="p-12 flex flex-col justify-center">
              <div className="inline-flex items-center gap-2 px-3 py-1 bg-gold-500/20 text-gold-300 text-xs font-semibold rounded-full mb-5 border border-gold-500/30 w-fit">
                <Zap size={11} /> Join 18,000+ Job Seekers
              </div>
              <h2 className="text-3xl md:text-4xl font-bold text-white leading-tight mb-4">
                Ready to Land Your<br />Next Big Role?
              </h2>
              <p className="text-navy-200 text-sm leading-relaxed mb-6 max-w-md">
                Subscribe to KC Systems Jobs and get instant access to 2,400+ live positions, one-click applications, real-time job alerts, and a dedicated career advisor.
              </p>
              <ul className="space-y-2 mb-8">
                {["Apply directly to top companies", "Job alerts for your exact skills", "Resume review & career coaching", "Priority listing in recruiter searches"].map((item) => (
                  <li key={item} className="flex items-center gap-2 text-sm text-white/90">
                    <CheckCircle2 size={14} className="text-gold-400 shrink-0" /> {item}
                  </li>
                ))}
              </ul>
              <div className="flex flex-wrap gap-3">
                <Link href="/register?plan=job_seeker" className="inline-flex items-center gap-2 px-6 py-3 bg-gold-500 text-white font-semibold text-sm rounded-xl hover:bg-gold-400 transition-colors">
                  Subscribe Now — $49/mo <ArrowRight size={15} />
                </Link>
                <Link href="/register" className="inline-flex items-center gap-2 px-6 py-3 bg-white/10 text-white font-medium text-sm rounded-xl hover:bg-white/20 transition-colors border border-white/20">
                  Free Account
                </Link>
              </div>
            </div>
            <div className="hidden md:flex items-center justify-center p-12">
              <div className="bg-white/10 backdrop-blur-sm border border-white/20 rounded-2xl p-6 w-full max-w-xs text-white">
                <div className="text-sm font-semibold mb-4 text-gold-300">Job Seeker Plan</div>
                <div className="text-4xl font-bold mb-1">$49</div>
                <div className="text-white/60 text-sm mb-6">per month</div>
                <ul className="space-y-3 text-sm">
                  {["Unlimited job applications", "Email & WhatsApp alerts", "Resume builder tool", "Career advisor (1 session/mo)", "Early access to new listings"].map((f) => (
                    <li key={f} className="flex items-center gap-2 text-white/90">
                      <CheckCircle2 size={13} className="text-gold-400 shrink-0" /> {f}
                    </li>
                  ))}
                </ul>
                <Link href="/register?plan=job_seeker" className="mt-6 block w-full py-3 bg-gold-500 hover:bg-gold-400 text-white text-center text-sm font-semibold rounded-xl transition-colors">
                  Get Started
                </Link>
              </div>
            </div>
          </div>
        </section>

        {/* Browse Job Categories */}
        <section>
          <div className="text-center mb-8">
            <div className="inline-flex items-center gap-2 px-3 py-1 bg-gold-50 text-gold-700 text-xs font-semibold rounded-full mb-3 border border-gold-100">
              <Briefcase size={11} /> Browse by Field
            </div>
            <h2 className="text-2xl font-bold text-navy-900 mb-2">Browse Job Categories</h2>
            <p className="text-neutral-500 text-sm max-w-xl mx-auto">Explore opportunities across all major industries — from tech to healthcare to creative roles.</p>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {categories.map(({ label, icon: Icon, count, color, href }) => (
              <Link
                key={label}
                href={href}
                className="group bg-white border border-neutral-200 rounded-2xl p-5 hover:shadow-md hover:border-navy-200 transition-all flex flex-col items-center text-center"
              >
                <div className={`w-14 h-14 rounded-2xl border flex items-center justify-center mb-3 transition-transform group-hover:scale-110 ${color}`}>
                  <Icon size={24} />
                </div>
                <div className="font-semibold text-neutral-900 text-sm group-hover:text-navy-700">{label}</div>
                <div className="text-xs text-neutral-400 mt-1">{count} open roles</div>
              </Link>
            ))}
          </div>
        </section>

        {/* Recent Jobs */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <div>
              <h2 className="text-2xl font-bold text-navy-900">Recent Jobs</h2>
              <p className="text-neutral-500 text-sm mt-0.5">Posted in the last 48 hours</p>
            </div>
            <Link href="/jobs" className="text-sm text-navy-700 hover:text-navy-900 font-medium flex items-center gap-1">
              View all <ArrowRight size={14} />
            </Link>
          </div>
          <div className="space-y-3">
            {recentJobsData.map((job) => (
              <Link
                key={job.id}
                href={`/jobs/${job.id}`}
                className="group bg-white rounded-2xl border border-neutral-200 p-5 flex items-center gap-5 hover:border-navy-300 hover:shadow-sm transition-all"
              >
                <div className="w-11 h-11 bg-navy-50 rounded-xl flex items-center justify-center shrink-0">
                  <Briefcase size={18} className="text-navy-600" />
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-navy-800 text-sm group-hover:text-navy-600 truncate">{job.title}</h3>
                  <div className="flex items-center gap-3 text-xs text-neutral-500 mt-1">
                    <span className="flex items-center gap-1"><Building2 size={11} /> {job.company}</span>
                    <span className="flex items-center gap-1"><MapPin size={11} /> {job.location}</span>
                    <span className={`px-2 py-0.5 rounded-full font-medium ${typeColors[job.type] ?? "bg-neutral-100 text-neutral-600"}`}>{job.type}</span>
                  </div>
                  <div className="flex gap-1.5 mt-1.5">
                    {job.tags.map((tag) => (
                      <span key={tag} className="text-xs bg-neutral-100 text-neutral-500 px-2 py-0.5 rounded-full">{tag}</span>
                    ))}
                  </div>
                </div>
                <div className="shrink-0 text-right">
                  <div className="text-sm font-semibold text-emerald-600">{job.salary}</div>
                  <div className="text-xs text-neutral-400 mt-1 flex items-center gap-1 justify-end"><Clock size={10} /> {job.posted}</div>
                </div>
                <ArrowRight size={15} className="text-neutral-300 group-hover:text-navy-600 shrink-0 transition-colors" />
              </Link>
            ))}
          </div>

          {/* Pagination */}
          <div className="flex justify-center gap-2 mt-8">
            {[1, 2, 3, 4, 5].map((p) => (
              <button
                key={p}
                className={`w-9 h-9 rounded-xl text-sm font-medium transition-colors ${p === 1 ? "bg-navy-700 text-white" : "bg-white border border-neutral-300 text-neutral-600 hover:border-navy-400"}`}
              >
                {p}
              </button>
            ))}
          </div>
        </section>

        {/* Bottom CTA strip */}
        <section className="bg-navy-900 rounded-3xl p-8 flex flex-col md:flex-row items-center justify-between gap-6">
          <div>
            <h3 className="text-xl font-bold text-white mb-1">Are you a recruiter or employer?</h3>
            <p className="text-navy-300 text-sm">Post your job listing and reach 18,000+ active job seekers on KC Systems.</p>
          </div>
          <div className="flex gap-3 shrink-0">
            <Link href="/register?type=employer" className="px-5 py-2.5 bg-gold-500 text-white text-sm font-semibold rounded-xl hover:bg-gold-400 transition-colors flex items-center gap-2">
              Post a Job <ArrowRight size={14} />
            </Link>
            <Link href="/register?type=employer" className="px-5 py-2.5 bg-white/10 text-white text-sm font-medium rounded-xl hover:bg-white/20 border border-white/20 transition-colors">
              View Pricing
            </Link>
          </div>
        </section>

      </div>
    </div>
  );
}
