/**
 * JobsList Component
 * Displays all jobs with filtering, editing, and deletion
 */

"use client";

import { useState, useEffect } from "react";
import {
  Search,
  Edit,
  Trash2,
  Eye,
  Calendar,
  MapPin,
  Briefcase,
} from "lucide-react";
import EditJobModal from "./EditJobModal";

interface Job {
  id: string;
  slug: string;
  title_translations: { ar: string; en: string };
  department: string;
  department_label: { ar: string; en: string };
  location_translations: { ar: string; en: string };
  status: string;
  opening_at: string;
  closing_at: string | null;
  created_at: string;
}

interface JobsListProps {
  userRole?: string;
  refreshTrigger: number;
  onJobUpdated: () => void;
}

export default function JobsList({
  userRole,
  refreshTrigger,
  onJobUpdated,
}: JobsListProps) {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [selectedJob, setSelectedJob] = useState<Job | null>(null);
  const [showEditModal, setShowEditModal] = useState(false);

  const canEdit = userRole && ["ADMIN", "SUPER_ADMIN"].includes(userRole);
  const canDelete = userRole === "SUPER_ADMIN";

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

  const fetchJobs = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (statusFilter !== "all") params.append("status", statusFilter);
      if (searchTerm) params.append("search", searchTerm);

      const response = await fetch(`/api/staff/jobs?${params.toString()}`);
      const data = await response.json();

      if (response.ok) {
        setJobs(data.jobs || []);
      } else {
        console.error("Failed to fetch jobs:", data.error);
      }
    } catch (error) {
      console.error("Error fetching jobs:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    fetchJobs();
  };

  const handleEdit = (job: Job) => {
    setSelectedJob(job);
    setShowEditModal(true);
  };

  const handleDelete = async (job: Job) => {
    if (
      !confirm(
        `Are you sure you want to archive "${job.title_translations.en}"?`,
      )
    ) {
      return;
    }

    try {
      const response = await fetch(`/api/staff/jobs/${job.id}`, {
        method: "DELETE",
      });

      if (response.ok) {
        alert("Job archived successfully");
        onJobUpdated();
      } else {
        const data = await response.json();
        alert(`Failed to archive job: ${data.error}`);
      }
    } catch (error) {
      console.error("Error deleting job:", error);
      alert("An error occurred while archiving the job");
    }
  };

  const getStatusBadge = (status: string) => {
    const badges = {
      draft: "bg-gray-100 text-gray-700 border-gray-300",
      open: "bg-green-100 text-green-700 border-green-300",
      paused: "bg-yellow-100 text-yellow-700 border-yellow-300",
      closed: "bg-red-100 text-red-700 border-red-300",
      archived: "bg-slate-100 text-slate-700 border-slate-300",
    };

    return (
      <span
        className={`px-3 py-1 rounded-full text-xs font-semibold border ${badges[status as keyof typeof badges] || badges.draft}`}
      >
        {status.toUpperCase()}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="text-center py-12">
        <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
        <p className="mt-4 text-gray-600">Loading jobs...</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Search by job title..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
            className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
        >
          <option value="all">All Statuses</option>
          <option value="draft">Draft</option>
          <option value="open">Open</option>
          <option value="paused">Paused</option>
          <option value="closed">Closed</option>
          <option value="archived">Archived</option>
        </select>
        <button
          onClick={handleSearch}
          className="px-6 py-2.5 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all"
        >
          Search
        </button>
      </div>

      {/* Jobs Table */}
      {jobs.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
          <Briefcase className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-600 font-medium">No jobs found</p>
          <p className="text-sm text-gray-500 mt-1">
            {statusFilter !== "all"
              ? "Try changing the filters"
              : "Create your first job posting"}
          </p>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Job Title
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Department
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Location
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Posted
                </th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-700 uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {jobs.map((job) => (
                <tr key={job.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-4">
                    <div className="font-medium text-brand-ink">
                      {job.title_translations.en}
                    </div>
                    <div className="text-sm text-gray-500 mt-0.5">
                      {job.title_translations.ar}
                    </div>
                  </td>
                  <td className="px-4 py-4">
                    <span className="text-sm text-gray-700">
                      {job.department_label.en}
                    </span>
                  </td>
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-1.5 text-sm text-gray-700">
                      <MapPin className="w-4 h-4 text-gray-400" />
                      {job.location_translations.en}
                    </div>
                  </td>
                  <td className="px-4 py-4">{getStatusBadge(job.status)}</td>
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-1.5 text-sm text-gray-600">
                      <Calendar className="w-4 h-4 text-gray-400" />
                      {new Date(job.opening_at).toLocaleDateString("en-US", {
                        month: "short",
                        day: "numeric",
                        year: "numeric",
                      })}
                    </div>
                  </td>
                  <td className="px-4 py-4">
                    <div className="flex items-center justify-end gap-2">
                      <a
                        href={`/en/careers#${job.slug}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="p-2 text-gray-600 hover:text-brand-green hover:bg-green-50 rounded-lg transition-all"
                        title="View on public page"
                        aria-label="View job on public page"
                      >
                        <Eye className="w-4 h-4" />
                      </a>
                      {canEdit && (
                        <button
                          onClick={() => handleEdit(job)}
                          className="p-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-all"
                          title="Edit job"
                          aria-label="Edit job"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                      )}
                      {canDelete && (
                        <button
                          onClick={() => handleDelete(job)}
                          className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-all"
                          title="Archive job"
                          aria-label="Archive job"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Edit Job Modal */}
      {showEditModal && selectedJob && (
        <EditJobModal
          isOpen={showEditModal}
          job={selectedJob}
          onClose={() => {
            setShowEditModal(false);
            setSelectedJob(null);
          }}
          onJobUpdated={() => {
            setShowEditModal(false);
            setSelectedJob(null);
            onJobUpdated();
          }}
        />
      )}
    </div>
  );
}
