"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft,
  MapPin,
  DollarSign,
  Users,
  Building2,
  Calendar,
  Briefcase,
  BarChart,
  Edit,
  Trash2,
  UserPlus,
  ChevronRight,
  FileText,
  Globe,
  Share2,
  ExternalLink,
  CheckCircle2,
  XCircle,
  Eye,
  Plus,
} from "lucide-react";

interface PipelineStage {
  id: number;
  name: string;
  order: number;
  type: string;
  candidates: any[];
}

interface JobBoardPosting {
  id: number;
  jobId: number;
  boardKey: string;
  boardName: string;
  status: string;
  externalUrl: string;
  externalId: string;
  viewsCount: number;
  applicantsCount: number;
  updatedAt: string;
}

interface JobDetail {
  id: number;
  title: string;
  location: string;
  type: string;
  experience: string;
  salaryMin: number | null;
  salaryMax: number | null;
  description: string;
  requirements: string;
  status: string;
  openPositions: number;
  createdAt: string;
  department: { name: string } | null;
  stages: PipelineStage[];
  boardPostings?: JobBoardPosting[];
  totalCandidates: number;
  totalInterviews: number;
}

export default function JobDetailPage() {
  const params = useParams();
  const router = useRouter();
  const jobId = params.id as string;
  const [job, setJob] = useState<JobDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState<{ role: string } | null>(null);
  const [canEditForms, setCanEditForms] = useState(false);
  const [updatingBoard, setUpdatingBoard] = useState<string | null>(null);

  async function toggleBoardPosting(boardKey: string, currentStatus: string) {
    setUpdatingBoard(boardKey);
    const newStatus = currentStatus === "posted" ? "unposted" : "posted";
    try {
      const res = await fetch(`/api/jobs/${jobId}/board-postings`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ boardKey, status: newStatus }),
      });
      if (res.ok) {
        const jobData = await fetch(`/api/jobs/${jobId}`).then((r) => r.json());
        setJob(jobData);
      }
    } catch (error) {
      console.error("Failed to update board posting:", error);
    } finally {
      setUpdatingBoard(null);
    }
  }

  useEffect(() => {
    Promise.all([
      fetch(`/api/jobs/${jobId}`).then((res) => res.json()),
      fetch("/api/me").then((res) => res.json()),
    ]).then(([jobData, me]) => {
      setJob(jobData);
      setCurrentUser(me.user);
      setCanEditForms(me.permissions.canManageForms);
      setLoading(false);
    });
  }, [jobId]);

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

  if (!job) {
    return (
      <div className="p-6 text-center text-gray-500">Job not found</div>
    );
  }

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

  const stageColors: Record<string, string> = {
    applied: "bg-gray-100 text-gray-700",
    screening: "bg-blue-100 text-blue-700",
    interview: "bg-purple-100 text-purple-700",
    assessment: "bg-amber-100 text-amber-700",
    offer: "bg-green-100 text-green-700",
    hired: "bg-emerald-100 text-emerald-700",
    rejected: "bg-red-100 text-red-700",
  };

  return (
    <div className="p-6">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-gray-500 mb-4">
        <Link href="/jobs" className="hover:text-blue-600 transition-colors">
          Jobs
        </Link>
        <ChevronRight className="w-4 h-4" />
        <span className="text-gray-900 font-medium">{job.title}</span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between mb-6">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <h1 className="text-2xl font-bold text-gray-900">{job.title}</h1>
            <span
              className={`badge ${
                job.status === "open" ? "badge-open" : "badge-closed"
              }`}
            >
              {job.status}
            </span>
          </div>
          <div className="flex items-center gap-4 text-sm text-gray-500">
            {job.department && (
              <span className="flex items-center gap-1.5">
                <Building2 className="w-4 h-4" />
                {job.department.name}
              </span>
            )}
            <span className="flex items-center gap-1.5">
              <MapPin className="w-4 h-4" />
              {job.location}
            </span>
            <span className="flex items-center gap-1.5">
              <DollarSign className="w-4 h-4" />
              {formatSalary(job.salaryMin, job.salaryMax)}
            </span>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Link
            href={`/jobs/${jobId}/applications`}
            className="flex items-center gap-2 px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm font-medium"
          >
            <FileText className="w-4 h-4" />
            {canEditForms ? "Application Form" : "View Application Form"}
          </Link>
          <Link
            href={`/jobs/${jobId}/pipeline`}
            className="flex items-center gap-2 px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
          >
            <BarChart className="w-4 h-4" />
            View Pipeline
          </Link>
          <button className="p-2.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">
            <Edit className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Users className="w-5 h-5 text-blue-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{job.totalCandidates}</p>
          <p className="text-sm text-gray-500">Total Applicants</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-purple-100 rounded-lg">
              <Briefcase className="w-5 h-5 text-purple-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{job.openPositions}</p>
          <p className="text-sm text-gray-500">Open Positions</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-green-100 rounded-lg">
              <Calendar className="w-5 h-5 text-green-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{job.totalInterviews}</p>
          <p className="text-sm text-gray-500">Interviews</p>
        </div>
      </div>

      {/* Job Board Postings & Multi-Channel Distribution */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6 mb-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-5 border-b border-gray-100">
          <div>
            <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <Share2 className="w-5 h-5 text-blue-600" />
              Job Distribution & External Posting Channels
            </h2>
            <p className="text-sm text-gray-500 mt-0.5">
              Control where this open job posting is distributed and monitor live application counts.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs bg-emerald-50 text-emerald-700 font-bold px-3 py-1 rounded-full border border-emerald-100">
              {job.boardPostings?.filter((b) => b.status === "posted").length || 0} Channels Active
            </span>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-5">
          {[
            { key: "google_jobs", name: "Google for Jobs", color: "bg-red-50 text-red-700 border-red-200", icon: "🌐" },
            { key: "indeed", name: "Indeed", color: "bg-blue-50 text-blue-700 border-blue-200", icon: "💼" },
            { key: "linkedin", name: "LinkedIn Jobs", color: "bg-indigo-50 text-indigo-700 border-indigo-200", icon: "👔" },
            { key: "ziprecruiter", name: "ZipRecruiter", color: "bg-emerald-50 text-emerald-700 border-emerald-200", icon: "🚀" },
            { key: "glassdoor", name: "Glassdoor", color: "bg-teal-50 text-teal-700 border-teal-200", icon: "🏢" },
            { key: "company_careers", name: "Company Careers Page", color: "bg-slate-100 text-slate-800 border-slate-200", icon: "🔗" },
          ].map((board) => {
            const posting = job.boardPostings?.find((p) => p.boardKey === board.key);
            const isPosted = posting?.status === "posted";
            const isLoading = updatingBoard === board.key;

            return (
              <div
                key={board.key}
                className={`p-4 rounded-xl border transition-all flex flex-col justify-between ${
                  isPosted ? "bg-white border-gray-200 shadow-xs" : "bg-gray-50/70 border-gray-200 opacity-80"
                }`}
              >
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className={`text-xs font-bold px-2.5 py-0.5 rounded-full border ${board.color} flex items-center gap-1`}>
                      <span>{board.icon}</span>
                      <span>{board.name}</span>
                    </span>

                    <button
                      onClick={() => toggleBoardPosting(board.key, posting?.status || "unposted")}
                      disabled={isLoading || !canEditForms}
                      className={`text-xs font-bold px-3 py-1 rounded-lg transition-colors flex items-center gap-1 disabled:opacity-50 ${
                        isPosted
                          ? "bg-emerald-100 text-emerald-800 hover:bg-red-100 hover:text-red-800"
                          : "bg-gray-200 text-gray-700 hover:bg-blue-600 hover:text-white"
                      }`}
                      title={isPosted ? "Click to remove from board" : "Click to publish to board"}
                    >
                      {isLoading ? (
                        "Updating..."
                      ) : isPosted ? (
                        <>
                          <CheckCircle2 className="w-3.5 h-3.5" />
                          <span>Posted</span>
                        </>
                      ) : (
                        <>
                          <Plus className="w-3.5 h-3.5" />
                          <span>Post Job</span>
                        </>
                      )}
                    </button>
                  </div>

                  {isPosted && posting ? (
                    <div className="space-y-2 mt-3 pt-2 border-t border-gray-100">
                      <div className="flex items-center justify-between text-xs text-gray-600">
                        <span className="flex items-center gap-1">
                          <Eye className="w-3.5 h-3.5 text-gray-400" />
                          {posting.viewsCount} Views
                        </span>
                        <span className="flex items-center gap-1 font-semibold text-gray-900">
                          <Users className="w-3.5 h-3.5 text-blue-600" />
                          {posting.applicantsCount} Applicants
                        </span>
                      </div>

                      {posting.externalUrl && (
                        <a
                          href={posting.externalUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 font-medium pt-1"
                        >
                          <span>View Live Listing</span>
                          <ExternalLink className="w-3 h-3" />
                        </a>
                      )}
                    </div>
                  ) : (
                    <p className="text-xs text-gray-400 italic mt-3 pt-2 border-t border-gray-100">
                      Not currently published on this job board.
                    </p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Description */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <h2 className="font-semibold text-gray-900 mb-4">Job Description</h2>
          <div className="text-gray-600 text-sm whitespace-pre-line">
            {job.description}
          </div>
        </div>

        {/* Requirements */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <h2 className="font-semibold text-gray-900 mb-4">Requirements</h2>
          <div className="text-gray-600 text-sm whitespace-pre-line">
            {job.requirements}
          </div>
        </div>
      </div>

      {/* Pipeline Overview */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 mt-6">
        <h2 className="font-semibold text-gray-900 mb-4">Pipeline Overview</h2>
        <div className="flex items-center gap-4 overflow-x-auto pb-2">
          {job.stages.filter(s => s.type !== 'rejected').map((stage) => (
            <div key={stage.id} className="flex items-center gap-2">
              <div
                className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
                  stageColors[stage.type] || "bg-gray-100 text-gray-700"
                }`}
              >
                {stage.name} ({stage.candidates.length})
              </div>
              {stage.order < (job.stages.filter(s => s.type !== 'rejected').length - 1) && (
                <ChevronRight className="w-4 h-4 text-gray-300" />
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
