"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Plus,
  Search,
  MapPin,
  Users,
  DollarSign,
  Building2,
  Clock,
  CheckCircle2,
  XCircle,
  Edit,
  Trash2,
  ExternalLink,
} from "lucide-react";

interface Job {
  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;
  candidateCount: number;
  pipelineCount?: number;
  postedBoards?: string[];
  department: { name: string } | null;
}

const DEFAULT_JOB_BOARDS = [
  { key: "google_jobs", name: "Google for Jobs", icon: "🌐", color: "border-red-200 text-red-800 bg-red-50/50" },
  { key: "indeed", name: "Indeed", icon: "💼", color: "border-blue-200 text-blue-800 bg-blue-50/50" },
  { key: "linkedin", name: "LinkedIn Jobs", icon: "👔", color: "border-indigo-200 text-indigo-800 bg-indigo-50/50" },
  { key: "ziprecruiter", name: "ZipRecruiter", icon: "🚀", color: "border-emerald-200 text-emerald-800 bg-emerald-50/50" },
  { key: "glassdoor", name: "Glassdoor", icon: "🏢", color: "border-teal-200 text-teal-800 bg-teal-50/50" },
  { key: "company_careers", name: "Company Careers Site", icon: "🔗", color: "border-slate-200 text-slate-800 bg-slate-100/50" },
];

export default function JobsPage() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedBoards, setSelectedBoards] = useState<string[]>(
    DEFAULT_JOB_BOARDS.map((b) => b.key)
  );

  const [newJob, setNewJob] = useState({
    title: "",
    departmentId: "",
    location: "Remote",
    type: "full-time",
    experience: "mid",
    salaryMin: "",
    salaryMax: "",
    description: "",
    requirements: "",
    openPositions: "1",
  });

  useEffect(() => {
    fetchJobs();
    fetchDepartments();
  }, []);

  async function fetchJobs() {
    const res = await fetch("/api/jobs");
    const data = await res.json();
    setJobs(data);
    setLoading(false);
  }

  async function fetchDepartments() {
    try {
      const res = await fetch("/api/departments");
      const data = await res.json();
      if (Array.isArray(data)) {
        setDepartments(data);
        if (data.length > 0 && !newJob.departmentId) {
          setNewJob((prev) => ({ ...prev, departmentId: String(data[0].id) }));
        }
      }
    } catch {
      /* ignore */
    }
  }

  function toggleBoardSelection(key: string) {
    setSelectedBoards((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
    );
  }

  async function handleCreateJob() {
    const res = await fetch("/api/jobs", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...newJob,
        departmentId: newJob.departmentId ? parseInt(newJob.departmentId) : null,
        postToBoards: selectedBoards,
      }),
    });
    if (res.ok) {
      setShowCreateModal(false);
      setNewJob({
        title: "",
        departmentId: departments[0]?.id ? String(departments[0].id) : "",
        location: "Remote",
        type: "full-time",
        experience: "mid",
        salaryMin: "",
        salaryMax: "",
        description: "",
        requirements: "",
        openPositions: "1",
      });
      setSelectedBoards(DEFAULT_JOB_BOARDS.map((b) => b.key));
      fetchJobs();
    }
  }

  async function toggleJobStatus(job: Job) {
    const newStatus = job.status === "open" ? "closed" : "open";
    await fetch(`/api/jobs/${job.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: newStatus }),
    });
    fetchJobs();
  }

  const filteredJobs = jobs.filter((job) => {
    const matchesSearch =
      job.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      job.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
      job.department?.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === "all" || job.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

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

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Jobs</h1>
          <p className="text-gray-500 mt-1">Manage your open positions and job postings</p>
        </div>
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2.5 rounded-lg hover:bg-blue-700 transition-colors font-medium"
        >
          <Plus className="w-5 h-5" />
          New Job
        </button>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 mb-6">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search jobs..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
        >
          <option value="all">All Status</option>
          <option value="open">Open</option>
          <option value="closed">Closed</option>
        </select>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {filteredJobs.map((job) => (
            <div
              key={job.id}
              className="bg-white rounded-xl border border-gray-200 shadow-sm hover:shadow-md transition-shadow p-5"
            >
              <div className="flex items-start justify-between mb-3">
                <Link href={`/jobs/${job.id}`} className="flex-1 min-w-0">
                  <h3 className="font-semibold text-gray-900 hover:text-blue-600 transition-colors truncate">
                    {job.title}
                  </h3>
                </Link>
                <span
                  className={`badge ${
                    job.status === "open" ? "badge-open" : job.status === "closed" ? "badge-closed" : "badge-draft"
                  }`}
                >
                  {job.status}
                </span>
              </div>

              {job.department && (
                <div className="flex items-center gap-1.5 text-sm text-gray-500 mb-2">
                  <Building2 className="w-4 h-4" />
                  {job.department.name}
                </div>
              )}

              <div className="space-y-2 text-sm text-gray-600 mb-4">
                <div className="flex items-center gap-2">
                  <MapPin className="w-4 h-4 text-gray-400" />
                  {job.location}
                </div>
                <div className="flex items-center gap-2">
                  <DollarSign className="w-4 h-4 text-gray-400" />
                  {formatSalary(job.salaryMin, job.salaryMax)}
                </div>
                <div className="flex items-center gap-2">
                  <Users className="w-4 h-4 text-gray-400" />
                  {job.candidateCount} applicant{job.candidateCount !== 1 ? "s" : ""} · {job.openPositions} position{job.openPositions !== 1 ? "s" : ""}
                </div>
                <div className="flex items-center gap-2">
                  <Clock className="w-4 h-4 text-gray-400" />
                  Posted {new Date(job.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                </div>
              </div>

              {/* Active Job Boards Badges */}
              {job.postedBoards && job.postedBoards.length > 0 && (
                <div className="mb-4 pt-3 border-t border-gray-100">
                  <p className="text-[11px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Active Job Boards</p>
                  <div className="flex flex-wrap gap-1">
                    {job.postedBoards.map((board) => {
                      const boardMap: Record<string, { label: string; bg: string }> = {
                        google_jobs: { label: "Google Jobs", bg: "bg-red-50 text-red-700 border-red-200" },
                        indeed: { label: "Indeed", bg: "bg-blue-50 text-blue-700 border-blue-200" },
                        linkedin: { label: "LinkedIn", bg: "bg-indigo-50 text-indigo-700 border-indigo-200" },
                        ziprecruiter: { label: "ZipRecruiter", bg: "bg-emerald-50 text-emerald-700 border-emerald-200" },
                        glassdoor: { label: "Glassdoor", bg: "bg-teal-50 text-teal-700 border-teal-200" },
                        company_careers: { label: "Careers Site", bg: "bg-slate-100 text-slate-800 border-slate-200" },
                      };
                      const b = boardMap[board] || { label: board, bg: "bg-gray-100 text-gray-700 border-gray-200" };
                      return (
                        <span key={board} className={`text-[10px] font-extrabold px-2 py-0.5 rounded-md border ${b.bg}`}>
                          {b.label}
                        </span>
                      );
                    })}
                  </div>
                </div>
              )}

              <div className="flex items-center gap-2 pt-3 border-t border-gray-100">
                <Link
                  href={`/jobs/${job.id}`}
                  className="flex-1 text-center py-2 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors"
                >
                  View Details
                </Link>
                <Link
                  href={`/jobs/${job.id}/pipeline`}
                  className="flex-1 text-center py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
                >
                  Pipeline <span className="font-semibold text-gray-900">({job.pipelineCount ?? job.candidateCount})</span>
                </Link>
                <button
                  onClick={() => toggleJobStatus(job)}
                  className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-50 rounded-lg transition-colors"
                  title={job.status === "open" ? "Close job" : "Reopen job"}
                >
                  {job.status === "open" ? (
                    <XCircle className="w-4 h-4" />
                  ) : (
                    <CheckCircle2 className="w-4 h-4" />
                  )}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create Job Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Create New Job</h2>
              <button
                onClick={() => setShowCreateModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <XCircle className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Job Title *</label>
                  <input
                    type="text"
                    value={newJob.title}
                    onChange={(e) => setNewJob({ ...newJob, title: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    placeholder="e.g., Senior Frontend Engineer"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Department</label>
                  <select
                    value={newJob.departmentId}
                    onChange={(e) => setNewJob({ ...newJob, departmentId: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="">No Department / Corporate</option>
                    {departments.map((dept) => (
                      <option key={dept.id} value={dept.id}>
                        {dept.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Location</label>
                  <input
                    type="text"
                    value={newJob.location}
                    onChange={(e) => setNewJob({ ...newJob, location: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    placeholder="e.g., Remote"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Job Type</label>
                  <select
                    value={newJob.type}
                    onChange={(e) => setNewJob({ ...newJob, type: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="full-time">Full-time</option>
                    <option value="part-time">Part-time</option>
                    <option value="contract">Contract</option>
                    <option value="internship">Internship</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Min Salary</label>
                  <input
                    type="number"
                    value={newJob.salaryMin}
                    onChange={(e) => setNewJob({ ...newJob, salaryMin: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    placeholder="e.g., 100000"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Max Salary</label>
                  <input
                    type="number"
                    value={newJob.salaryMax}
                    onChange={(e) => setNewJob({ ...newJob, salaryMax: e.target.value })}
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    placeholder="e.g., 150000"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Experience Level</label>
                <select
                  value={newJob.experience}
                  onChange={(e) => setNewJob({ ...newJob, experience: e.target.value })}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                >
                  <option value="entry">Entry Level</option>
                  <option value="mid">Mid Level</option>
                  <option value="senior">Senior Level</option>
                  <option value="lead">Lead/Principal</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Open Positions</label>
                <input
                  type="number"
                  value={newJob.openPositions}
                  onChange={(e) => setNewJob({ ...newJob, openPositions: e.target.value })}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  min="1"
                />
              </div>

              {/* Job Board Distribution Platforms Selector */}
              <div className="p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3">
                <div className="flex items-center justify-between">
                  <div>
                    <label className="block text-xs font-bold uppercase text-slate-700 tracking-wider">
                      Post Job To Distribution Channels
                    </label>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Select external job boards to automatically publish this posting upon creation.
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => setSelectedBoards(DEFAULT_JOB_BOARDS.map((b) => b.key))}
                      className="text-xs text-blue-600 font-semibold hover:underline"
                    >
                      Select All
                    </button>
                    <span className="text-gray-300">|</span>
                    <button
                      type="button"
                      onClick={() => setSelectedBoards([])}
                      className="text-xs text-slate-500 font-semibold hover:underline"
                    >
                      Clear
                    </button>
                  </div>
                </div>

                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 pt-1">
                  {DEFAULT_JOB_BOARDS.map((board) => {
                    const isChecked = selectedBoards.includes(board.key);
                    return (
                      <label
                        key={board.key}
                        onClick={() => toggleBoardSelection(board.key)}
                        className={`p-2.5 rounded-lg border text-xs font-semibold flex items-center gap-2 cursor-pointer transition-all select-none ${
                          isChecked
                            ? `${board.color} shadow-2xs font-bold`
                            : "border-gray-200 bg-white text-gray-400 opacity-60 hover:opacity-100"
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={isChecked}
                          onChange={() => {}} // handled by container onClick
                          className="w-3.5 h-3.5 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                        />
                        <span>{board.icon}</span>
                        <span className="truncate">{board.name}</span>
                      </label>
                    );
                  })}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Description *</label>
                <textarea
                  value={newJob.description}
                  onChange={(e) => setNewJob({ ...newJob, description: e.target.value })}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-24 resize-none"
                  placeholder="Describe the role and responsibilities..."
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Requirements</label>
                <textarea
                  value={newJob.requirements}
                  onChange={(e) => setNewJob({ ...newJob, requirements: e.target.value })}
                  className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-24 resize-none"
                  placeholder="List the requirements (one per line)..."
                />
              </div>
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateJob}
                disabled={!newJob.title || !newJob.description}
                className="px-4 py-2.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Create Job
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
