"use client";

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

interface JobDetail {
  id: number;
  title: string;
  location: string;
  type: string;
  experience: string;
  salaryMin: number | null;
  salaryMax: number | null;
  description: string;
  requirements: string;
  openPositions: number;
  department: { name: string } | null;
  boardPostings?: Array<{
    id: number;
    boardKey: string;
    boardName: string;
    status: string;
    externalUrl: string;
    viewsCount: number;
    applicantsCount: number;
  }>;
}

const BOARD_ICONS: Record<string, string> = {
  google_jobs: "🌐",
  indeed: "💼",
  linkedin: "👔",
  ziprecruiter: "🚀",
  glassdoor: "🏢",
  company_careers: "🔗",
};

export default function CareersJobDetailPage() {
  const params = useParams();
  const jobId = params.id as string;
  const [job, setJob] = useState<JobDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/jobs/${jobId}`)
      .then((res) => res.json())
      .then((data) => {
        setJob(data);
        setLoading(false);
      });
  }, [jobId]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600" />
      </div>
    );
  }

  if (!job) {
    return (
      <div className="min-h-screen flex items-center justify-center text-gray-500">
        Job posting not found.
      </div>
    );
  }

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

  const activeBoards = (job.boardPostings || []).filter((b) => b.status === "posted");

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Hero Header */}
      <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 75% 50%, white 2px, transparent 2px)", backgroundSize: "40px 40px" }} />
        <div className="relative max-w-4xl mx-auto px-6 py-12">
          <Link
            href="/careers"
            className="inline-flex items-center gap-1.5 text-sm font-bold text-blue-200 hover:text-white transition-colors mb-6"
          >
            <ArrowLeft className="w-4 h-4" /> Back to All Positions
          </Link>

          <div className="flex items-start gap-4">
            <div className="w-14 h-14 rounded-2xl bg-white/10 border border-white/20 flex items-center justify-center text-2xl font-black shrink-0">
              {job.title[0]}
            </div>
            <div>
              <h1 className="text-2xl md:text-4xl font-black tracking-tight leading-tight">{job.title}</h1>
              <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 mt-3 text-sm text-blue-100 font-medium">
                <span className="flex items-center gap-1"><Building2 className="w-4 h-4" /> {job.department?.name || "Corporate"}</span>
                <span className="flex items-center gap-1"><MapPin className="w-4 h-4" /> {job.location}</span>
                <span className="flex items-center gap-1"><Briefcase className="w-4 h-4" /> {job.type.replace("-", " ")}</span>
                <span className="flex items-center gap-1"><DollarSign className="w-4 h-4" /> {formatSalary(job.salaryMin, job.salaryMax)}</span>
                <span className="flex items-center gap-1"><Users className="w-4 h-4" /> {job.openPositions} opening{job.openPositions > 1 ? "s" : ""}</span>
              </div>
            </div>
          </div>

          <div className="mt-8 flex flex-wrap items-center gap-3">
            <Link
              href={`/jobs/${jobId}/applications/preview`}
              className="inline-flex items-center gap-2 px-6 py-3.5 bg-white text-indigo-700 font-black rounded-xl shadow-lg hover:bg-blue-50 transition-colors text-sm"
            >
              Apply Now <ArrowRight className="w-4 h-4" />
            </Link>
            <Link
              href="/careers"
              className="inline-flex items-center gap-2 px-5 py-3.5 bg-white/10 border border-white/20 text-white font-bold rounded-xl hover:bg-white/20 transition-colors text-sm"
            >
              <Share2 className="w-4 h-4" /> Share Posting
            </Link>
          </div>
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-6 py-10 space-y-8">
        {/* Job Description */}
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 md:p-8">
          <h2 className="text-xl font-bold text-gray-900 border-b border-gray-100 pb-3 mb-4">
            Position Overview
          </h2>
          <div className="text-sm text-gray-700 leading-relaxed whitespace-pre-line">
            {job.description}
          </div>
        </div>

        {/* Requirements */}
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 md:p-8">
          <h2 className="text-xl font-bold text-gray-900 border-b border-gray-100 pb-3 mb-4">
            Qualifications & Requirements
          </h2>
          <div className="text-sm text-gray-700 leading-relaxed whitespace-pre-line">
            {job.requirements}
          </div>
        </div>

        {/* Distribution Channels */}
        {activeBoards.length > 0 && (
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 md:p-8">
            <h2 className="text-lg font-bold text-gray-900 border-b border-gray-100 pb-3 mb-4">
              Also Available On
            </h2>
            <div className="flex flex-wrap gap-3">
              {activeBoards.map((board) => (
                <a
                  key={board.id}
                  href={board.externalUrl || "#"}
                  target="_blank"
                  rel="noreferrer"
                  className="flex items-center gap-2 px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-sm font-semibold text-gray-700 hover:bg-gray-100 hover:border-gray-300 transition-colors"
                >
                  <span>{BOARD_ICONS[board.boardKey] || "📌"}</span>
                  <span>{board.boardName}</span>
                  <ExternalLink className="w-3.5 h-3.5 text-gray-400" />
                </a>
              ))}
            </div>
          </div>
        )}

        {/* CTA Card */}
        <div className="bg-gradient-to-r from-indigo-600 to-blue-700 rounded-2xl shadow-lg p-6 md:p-8 text-white text-center">
          <h3 className="text-xl font-black mb-2">Ready to Apply?</h3>
          <p className="text-blue-100 text-sm mb-5 max-w-md mx-auto">
            Submit your application directly through our secure portal. It only takes a few minutes.
          </p>
          <Link
            href={`/jobs/${jobId}/applications/preview`}
            className="inline-flex items-center gap-2 px-8 py-3.5 bg-white text-indigo-700 font-black rounded-xl shadow-md hover:bg-blue-50 transition-colors text-sm"
          >
            Start Application <ArrowRight className="w-4 h-4" />
          </Link>
        </div>

        <div className="text-center pt-4">
          <Link
            href="/careers"
            className="inline-flex items-center gap-1.5 text-sm font-bold text-indigo-600 hover:text-indigo-800"
          >
            <ArrowLeft className="w-4 h-4" /> View All Open Positions
          </Link>
        </div>
      </div>
    </div>
  );
}
