"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  ArrowRight,
  Briefcase,
  Building2,
  DollarSign,
  ExternalLink,
  MapPin,
  Search,
  Share2,
  Users,
} from "lucide-react";

interface PublicJob {
  id: number;
  title: string;
  location: string;
  type: string;
  experience: string;
  salaryMin: number | null;
  salaryMax: number | null;
  description: string;
  department: { name: string } | null;
  candidateCount: number;
  openPositions: number;
  postedBoards?: string[];
  createdAt: string;
}

const BOARD_LABELS: Record<string, { label: string; emoji: string }> = {
  google_jobs: { label: "Google Jobs", emoji: "🌐" },
  indeed: { label: "Indeed", emoji: "💼" },
  linkedin: { label: "LinkedIn", emoji: "👔" },
  ziprecruiter: { label: "ZipRecruiter", emoji: "🚀" },
  glassdoor: { label: "Glassdoor", emoji: "🏢" },
  company_careers: { label: "Careers Site", emoji: "🔗" },
};

export default function CareersPage() {
  const [jobs, setJobs] = useState<PublicJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [deptFilter, setDeptFilter] = useState("all");

  useEffect(() => {
    fetch("/api/jobs?status=open")
      .then((res) => res.json())
      .then((data) => {
        setJobs(Array.isArray(data) ? data : []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const departments = Array.from(
    new Set(jobs.map((j) => j.department?.name).filter(Boolean) as string[])
  );

  const filteredJobs = jobs.filter((job) => {
    const query = search.toLowerCase();
    const matchesSearch =
      !query ||
      job.title.toLowerCase().includes(query) ||
      job.location.toLowerCase().includes(query) ||
      (job.department?.name || "").toLowerCase().includes(query);
    const matchesDept = deptFilter === "all" || job.department?.name === deptFilter;
    return matchesSearch && matchesDept;
  });

  const formatSalary = (min: number | null, max: number | null) => {
    if (!min && !max) return "Competitive";
    if (min && max) return `$${(min / 1000).toFixed(0)}k - $${(max / 1000).toFixed(0)}k`;
    return `$${((min || max)! / 1000).toFixed(0)}k`;
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white">
      {/* Hero Banner */}
      <div className="bg-gradient-to-r from-indigo-700 via-blue-700 to-purple-800 text-white relative overflow-hidden">
        <div className="absolute inset-0 opacity-10" style={{ backgroundImage: "radial-gradient(circle at 25% 50%, white 2px, transparent 2px)", backgroundSize: "40px 40px" }} />
        <div className="relative max-w-6xl mx-auto px-6 py-16 md:py-24 text-center">
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/10 border border-white/20 text-sm font-bold mb-6">
            <Building2 className="w-4 h-4" /> Corporate Career Opportunities
          </div>
          <h1 className="text-3xl md:text-5xl font-black tracking-tight leading-tight">
            Build Your Career With Us
          </h1>
          <p className="text-lg md:text-xl text-blue-100 mt-4 max-w-2xl mx-auto leading-relaxed">
            Join a team that values innovation, growth, and collaboration. Explore our open positions and find your next opportunity.
          </p>

          {/* Quick Stats */}
          <div className="flex flex-wrap items-center justify-center gap-6 md:gap-12 mt-10 pt-8 border-t border-white/10">
            <div className="text-center">
              <p className="text-3xl font-black">{jobs.length}</p>
              <p className="text-sm text-blue-200 font-medium">Open Positions</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-black">{departments.length}</p>
              <p className="text-sm text-blue-200 font-medium">Departments Hiring</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-black">{jobs.reduce((sum, j) => sum + j.openPositions, 0)}</p>
              <p className="text-sm text-blue-200 font-medium">Total Openings</p>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-6 py-8 md:py-12">
        {/* Search & Filter Bar */}
        <div className="flex flex-col md:flex-row items-stretch md:items-center gap-3 mb-8 sticky top-0 z-10 bg-white/90 backdrop-blur-sm py-3 -mx-6 px-6 border-b border-gray-100">
          <div className="relative flex-1">
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by job title, location, or department..."
              className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none shadow-sm"
            />
          </div>
          <select
            value={deptFilter}
            onChange={(e) => setDeptFilter(e.target.value)}
            className="px-4 py-3 rounded-xl border border-gray-200 text-sm font-medium focus:ring-2 focus:ring-indigo-500 focus:outline-none shadow-sm bg-white"
          >
            <option value="all">All Departments</option>
            {departments.map((dept) => (
              <option key={dept} value={dept}>{dept}</option>
            ))}
          </select>
        </div>

        {/* Job Listings */}
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600" />
          </div>
        ) : filteredJobs.length === 0 ? (
          <div className="text-center py-20 space-y-3">
            <Briefcase className="w-12 h-12 text-gray-300 mx-auto" />
            <h3 className="text-lg font-bold text-gray-800">No positions match your search</h3>
            <p className="text-sm text-gray-500">Try adjusting your search terms or department filter.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            {filteredJobs.map((job) => (
              <Link
                key={job.id}
                href={`/careers/${job.id}`}
                className="group bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-lg hover:border-indigo-300 transition-all p-6 flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-start justify-between gap-3 mb-3">
                    <div className="flex items-center gap-3">
                      <div className="w-11 h-11 rounded-xl bg-indigo-100 text-indigo-700 flex items-center justify-center font-black shrink-0">
                        {job.title[0]}
                      </div>
                      <div>
                        <h3 className="font-bold text-gray-900 text-base group-hover:text-indigo-700 transition-colors leading-tight">
                          {job.title}
                        </h3>
                        <p className="text-xs text-gray-400 font-medium">
                          {job.department?.name || "Corporate"}
                        </p>
                      </div>
                    </div>
                    <span className="text-[10px] font-extrabold px-2.5 py-1 rounded-full bg-indigo-50 text-indigo-700 border border-indigo-100 shrink-0">
                      {job.openPositions} OPENING{job.openPositions > 1 ? "S" : ""}
                    </span>
                  </div>

                  {/* Job Meta */}
                  <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-gray-500 font-medium mt-2">
                    <span className="flex items-center gap-1"><MapPin className="w-3.5 h-3.5 text-gray-400" /> {job.location}</span>
                    <span className="flex items-center gap-1"><Briefcase className="w-3.5 h-3.5 text-gray-400" /> {job.type.replace("-", " ")}</span>
                    <span className="flex items-center gap-1"><DollarSign className="w-3.5 h-3.5 text-gray-400" /> {formatSalary(job.salaryMin, job.salaryMax)}</span>
                    <span className="flex items-center gap-1 capitalize"><Users className="w-3.5 h-3.5 text-gray-400" /> {job.experience} level</span>
                  </div>

                  {/* Posted Boards */}
                  {job.postedBoards && job.postedBoards.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-3 pt-3 border-t border-gray-100">
                      <span className="text-[10px] font-bold text-gray-400 uppercase mr-1">Also posted on:</span>
                      {job.postedBoards.slice(0, 4).map((board) => {
                        const b = BOARD_LABELS[board];
                        return b ? (
                          <span key={board} className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-600 font-medium">
                            {b.emoji} {b.label}
                          </span>
                        ) : null;
                      })}
                    </div>
                  )}
                </div>

                {/* CTA */}
                <div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
                  <span className="text-xs text-gray-400 font-medium">
                    {job.candidateCount} applicant{job.candidateCount !== 1 ? "s" : ""}
                  </span>
                  <span className="flex items-center gap-1.5 text-sm font-bold text-indigo-600 group-hover:gap-2 transition-all">
                    View & Apply <ArrowRight className="w-4 h-4" />
                  </span>
                </div>
              </Link>
            ))}
          </div>
        )}

        {/* Footer */}
        <div className="text-center mt-12 pt-8 border-t border-gray-100">
          <p className="text-sm text-gray-400">
            Equal Opportunity Employer. We celebrate diversity and are committed to creating an inclusive environment for all employees.
          </p>
          <Link
            href="/"
            className="inline-flex items-center gap-1.5 text-sm font-bold text-indigo-600 hover:text-indigo-800 mt-3"
          >
            Return to Dashboard <ExternalLink className="w-3.5 h-3.5" />
          </Link>
        </div>
      </div>
    </div>
  );
}
