"use client";

import { useMemo, useState, useTransition } from "react";
import {
  Briefcase,
  Plus,
  Edit2,
  Trash2,
  Loader2,
  CheckCircle,
  XCircle,
  Star,
  StarOff,
  Database,
  RefreshCw,
  Images,
  Users,
  FileDown,
  Eye,
  EyeOff,
  X,
} from "lucide-react";
import {
  saveJobAction,
  deleteJobAction,
  toggleJobFeaturedAction,
  saveJobSlideAction,
  deleteJobSlideAction,
  saveJobApiSourceAction,
  deleteJobApiSourceAction,
  syncJobsFromApiSourceAction,
  updateApplicationStatusAction,
  deleteApplicationAction,
  toggleUserActiveAction,
} from "./actions";

type JobRow = {
  id: string;
  title: string;
  company: string | null;
  location: string | null;
  jobType: string | null;
  salary: string | null;
  source: string | null;
  isFeatured: boolean;
  isActive: boolean;
  postedAt: string | null;
  createdAt: string;
  applyLink: string | null;
  description: string | null;
  _count: { applications: number };
};

type JobSlide = {
  id: string;
  imageUrl: string;
  label: string;
  title: string;
  subtitle: string;
  isActive: boolean;
  sortOrder: number;
};

type JobApiSource = {
  id: string;
  name: string;
  sourceKey: string;
  endpoint: string;
  isActive: boolean;
  authHeader: string;
  authToken: string;
  jobPath: string;
  titleKey: string;
  companyKey: string;
  locationKey: string;
  typeKey: string;
  salaryKey: string;
  descriptionKey: string;
  applyLinkKey: string;
  postedAtKey: string;
  externalIdKey: string;
};

type ApplicationRow = {
  id: string;
  status: "submitted" | "viewed" | "shortlisted" | "rejected";
  createdAt: string;
  resumeUrl: string | null;
  coverLetter: string | null;
  job: { id: string; title: string; company: string | null };
  user: {
    id: string;
    name: string;
    email: string;
    isActive: boolean;
    jobSeekerProfile: { resumeUrl: string | null } | null;
  };
};

type SeekerRow = {
  id: string;
  name: string;
  email: string;
  isActive: boolean;
  createdAt: string;
  jobSeekerProfile: {
    phone: string | null;
    skills: string | null;
    experience: string | null;
    resumeUrl: string | null;
  } | null;
  _count: { jobApplications: number };
};

type Props = {
  jobs: JobRow[];
  slides: JobSlide[];
  apiSources: JobApiSource[];
  applications: ApplicationRow[];
  seekers: SeekerRow[];
};

type TabId = "jobs" | "api" | "slider" | "applications" | "seekers";

function useToast() {
  const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
  function show(type: "ok" | "err", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }
  const Toast = msg ? (
    <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg text-sm font-medium border ${msg.type === "ok" ? "bg-emerald-50 text-emerald-800 border-emerald-200" : "bg-red-50 text-red-700 border-red-200"}`}>
      {msg.type === "ok" ? <CheckCircle size={16} /> : <XCircle size={16} />}
      {msg.text}
    </div>
  ) : null;
  return { show, Toast };
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-neutral-100">
          <h3 className="font-bold text-neutral-800">{title}</h3>
          <button onClick={onClose} className="text-neutral-400 hover:text-neutral-600"><X size={18} /></button>
        </div>
        <div className="p-6">{children}</div>
      </div>
    </div>
  );
}

const TABS: { id: TabId; label: string; icon: React.ComponentType<{ size?: number }> }[] = [
  { id: "jobs", label: "Jobs", icon: Briefcase },
  { id: "api", label: "API Sources", icon: Database },
  { id: "slider", label: "Slider", icon: Images },
  { id: "applications", label: "Applications", icon: FileDown },
  { id: "seekers", label: "Job Seekers CRM", icon: Users },
];

export default function AdminJobsClient({ jobs, slides, apiSources, applications, seekers }: Props) {
  const [tab, setTab] = useState<TabId>("jobs");
  const [isPending, startTransition] = useTransition();
  const { show, Toast } = useToast();

  const [jobModal, setJobModal] = useState<JobRow | "new" | null>(null);
  const [slideModal, setSlideModal] = useState<JobSlide | "new" | null>(null);
  const [sourceModal, setSourceModal] = useState<JobApiSource | "new" | null>(null);

  const [slideFile, setSlideFile] = useState<File | null>(null);

  const [jobForm, setJobForm] = useState({
    title: "",
    company: "",
    location: "",
    jobType: "",
    salary: "",
    description: "",
    applyLink: "",
    source: "manual",
    isFeatured: false,
    isActive: true,
  });

  const [slideForm, setSlideForm] = useState({
    imageUrl: "",
    label: "",
    title: "",
    subtitle: "",
    sortOrder: 0,
    isActive: true,
  });

  const [sourceForm, setSourceForm] = useState({
    name: "",
    sourceKey: "",
    endpoint: "",
    isActive: true,
    authHeader: "",
    authToken: "",
    jobPath: "",
    titleKey: "title",
    companyKey: "company",
    locationKey: "location",
    typeKey: "jobType",
    salaryKey: "salary",
    descriptionKey: "description",
    applyLinkKey: "applyLink",
    postedAtKey: "postedAt",
    externalIdKey: "id",
  });

  const stats = useMemo(() => ({
    jobs: jobs.length,
    featured: jobs.filter((j) => j.isFeatured).length,
    applications: applications.length,
    seekers: seekers.length,
  }), [jobs, applications, seekers]);

  function openJobModal(job: JobRow | "new") {
    if (job === "new") {
      setJobForm({ title: "", company: "", location: "", jobType: "", salary: "", description: "", applyLink: "", source: "manual", isFeatured: false, isActive: true });
    } else {
      setJobForm({
        title: job.title,
        company: job.company || "",
        location: job.location || "",
        jobType: job.jobType || "",
        salary: job.salary || "",
        description: job.description || "",
        applyLink: job.applyLink || "",
        source: job.source || "manual",
        isFeatured: job.isFeatured,
        isActive: job.isActive,
      });
    }
    setJobModal(job);
  }

  function openSlideModal(slide: JobSlide | "new") {
    if (slide === "new") {
      setSlideForm({ imageUrl: "", label: "", title: "", subtitle: "", sortOrder: slides.length, isActive: true });
    } else {
      setSlideForm({ imageUrl: slide.imageUrl, label: slide.label, title: slide.title, subtitle: slide.subtitle, sortOrder: slide.sortOrder, isActive: slide.isActive });
    }
    setSlideFile(null);
    setSlideModal(slide);
  }

  function openSourceModal(source: JobApiSource | "new") {
    if (source === "new") {
      setSourceForm({
        name: "",
        sourceKey: "",
        endpoint: "",
        isActive: true,
        authHeader: "",
        authToken: "",
        jobPath: "",
        titleKey: "title",
        companyKey: "company",
        locationKey: "location",
        typeKey: "jobType",
        salaryKey: "salary",
        descriptionKey: "description",
        applyLinkKey: "applyLink",
        postedAtKey: "postedAt",
        externalIdKey: "id",
      });
    } else {
      setSourceForm({ ...source });
    }
    setSourceModal(source);
  }

  function saveJob() {
    startTransition(async () => {
      const fd = new FormData();
      if (jobModal !== "new") fd.append("id", (jobModal as JobRow).id);
      Object.entries(jobForm).forEach(([k, v]) => fd.append(k, String(v)));

      const res = await saveJobAction(fd);
      if (res.ok) {
        show("ok", jobModal === "new" ? "Job created" : "Job updated");
        setJobModal(null);
      } else {
        show("err", res.error || "Failed to save job");
      }
    });
  }

  function saveSlide() {
    startTransition(async () => {
      const fd = new FormData();
      if (slideModal !== "new") fd.append("id", (slideModal as JobSlide).id);
      Object.entries(slideForm).forEach(([k, v]) => fd.append(k, String(v)));
      if (slideFile) fd.append("imageFile", slideFile);

      const res = await saveJobSlideAction(fd);
      if (res.ok) {
        show("ok", slideModal === "new" ? "Slide created" : "Slide updated");
        setSlideModal(null);
      } else {
        show("err", res.error || "Failed to save slide");
      }
    });
  }

  function saveSource() {
    startTransition(async () => {
      const fd = new FormData();
      if (sourceModal !== "new") fd.append("id", (sourceModal as JobApiSource).id);
      Object.entries(sourceForm).forEach(([k, v]) => fd.append(k, String(v)));

      const res = await saveJobApiSourceAction(fd);
      if (res.ok) {
        show("ok", sourceModal === "new" ? "API source created" : "API source updated");
        setSourceModal(null);
      } else {
        show("err", res.error || "Failed to save source");
      }
    });
  }

  return (
    <div className="p-8">
      {Toast}

      <div className="mb-7">
        <h1 className="text-2xl font-bold text-neutral-900">Jobs Management</h1>
        <p className="text-neutral-500 text-sm mt-0.5">Manage jobs, API sync, slider, seekers CRM, and applications.</p>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-white border border-neutral-200 rounded-xl p-4"><div className="text-xs text-neutral-500">Jobs</div><div className="text-xl font-bold text-neutral-900">{stats.jobs}</div></div>
        <div className="bg-white border border-neutral-200 rounded-xl p-4"><div className="text-xs text-neutral-500">Featured</div><div className="text-xl font-bold text-neutral-900">{stats.featured}</div></div>
        <div className="bg-white border border-neutral-200 rounded-xl p-4"><div className="text-xs text-neutral-500">Applications</div><div className="text-xl font-bold text-neutral-900">{stats.applications}</div></div>
        <div className="bg-white border border-neutral-200 rounded-xl p-4"><div className="text-xs text-neutral-500">Job Seekers</div><div className="text-xl font-bold text-neutral-900">{stats.seekers}</div></div>
      </div>

      <div className="flex gap-2 mb-6 border-b border-neutral-200">
        {TABS.map((t) => {
          const Icon = t.icon;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === t.id ? "border-navy-600 text-navy-700" : "border-transparent text-neutral-500 hover:text-neutral-700"}`}>
              <Icon size={16} /> {t.label}
            </button>
          );
        })}
      </div>

      {tab === "jobs" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Jobs ({jobs.length})</h2>
            <button onClick={() => openJobModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add Job
            </button>
          </div>
          <div className="bg-white border border-neutral-200 rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 border-b border-neutral-200">
                <tr>
                  <th className="px-4 py-3 text-left">Job</th>
                  <th className="px-4 py-3 text-left">Source</th>
                  <th className="px-4 py-3 text-left">Type</th>
                  <th className="px-4 py-3 text-left">Applications</th>
                  <th className="px-4 py-3 text-left">Status</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {jobs.map((j) => (
                  <tr key={j.id}>
                    <td className="px-4 py-3">
                      <div className="font-medium text-neutral-800">{j.title}</div>
                      <div className="text-xs text-neutral-500">{j.company || "Unknown company"} · {j.location || "Unknown location"}</div>
                    </td>
                    <td className="px-4 py-3 text-xs text-neutral-600">{j.source || "manual"}</td>
                    <td className="px-4 py-3 text-xs text-neutral-600">{j.jobType || "-"}</td>
                    <td className="px-4 py-3 text-xs text-neutral-600">{j._count.applications}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2 py-0.5 text-xs rounded-full ${j.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-100 text-neutral-600"}`}>{j.isActive ? "Active" : "Hidden"}</span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex justify-end gap-2">
                        <button onClick={() => startTransition(async () => {
                          const res = await toggleJobFeaturedAction(j.id, !j.isFeatured);
                          if (res.ok) show("ok", j.isFeatured ? "Removed featured" : "Marked featured");
                        })} className="p-2 text-neutral-400 hover:text-amber-600">{j.isFeatured ? <Star size={16} /> : <StarOff size={16} />}</button>
                        <button onClick={() => openJobModal(j)} className="p-2 text-neutral-400 hover:text-blue-600"><Edit2 size={16} /></button>
                        <button onClick={() => startTransition(async () => {
                          if (confirm("Delete this job?")) {
                            await deleteJobAction(j.id);
                            show("ok", "Job deleted");
                          }
                        })} className="p-2 text-neutral-400 hover:text-red-600"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "api" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">API Sources ({apiSources.length})</h2>
            <button onClick={() => openSourceModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add API Source
            </button>
          </div>
          <div className="grid gap-3">
            {apiSources.map((s) => (
              <div key={s.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-start justify-between gap-4">
                <div>
                  <div className="font-semibold text-neutral-900">{s.name}</div>
                  <div className="text-xs text-neutral-500 mt-0.5">{s.endpoint}</div>
                  <div className="text-xs text-neutral-500 mt-1">path: {s.jobPath || "(root)"} · source: {s.sourceKey}</div>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => startTransition(async () => {
                    const res = await syncJobsFromApiSourceAction(s.id);
                    if (res.ok) {
                      show("ok", `Synced. Created ${res.created}, updated ${res.updated}, skipped ${res.skipped}.`);
                    } else {
                      show("err", res.error || "Sync failed");
                    }
                  })} className="inline-flex items-center gap-1 px-3 py-2 border border-neutral-200 rounded-lg text-sm text-neutral-700 hover:border-navy-300">
                    <RefreshCw size={14} /> Sync
                  </button>
                  <button onClick={() => openSourceModal(s)} className="p-2 text-neutral-400 hover:text-blue-600"><Edit2 size={16} /></button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this API source?")) {
                      await deleteJobApiSourceAction(s.id);
                      show("ok", "API source deleted");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600"><Trash2 size={16} /></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "slider" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Jobs Slider ({slides.length})</h2>
            <button onClick={() => openSlideModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800"><Plus size={16} /> Add Slide</button>
          </div>
          <div className="grid gap-3">
            {slides.map((s) => (
              <div key={s.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-center justify-between gap-4">
                <div className="min-w-0">
                  <div className="font-semibold text-neutral-900">{s.title}</div>
                  <div className="text-xs text-neutral-500 mt-0.5">{s.label}</div>
                  <div className="text-xs text-neutral-500 mt-0.5">order: {s.sortOrder}</div>
                </div>
                <div className="flex gap-2 items-center">
                  <span className={`inline-flex px-2 py-0.5 text-xs rounded-full ${s.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-100 text-neutral-600"}`}>{s.isActive ? "Active" : "Hidden"}</span>
                  <button onClick={() => openSlideModal(s)} className="p-2 text-neutral-400 hover:text-blue-600"><Edit2 size={16} /></button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this slide?")) {
                      await deleteJobSlideAction(s.id);
                      show("ok", "Slide deleted");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600"><Trash2 size={16} /></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "applications" && (
        <div>
          <h2 className="text-lg font-semibold text-neutral-800 mb-4">Applications ({applications.length})</h2>
          <div className="bg-white border border-neutral-200 rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 border-b border-neutral-200">
                <tr>
                  <th className="px-4 py-3 text-left">Applicant</th>
                  <th className="px-4 py-3 text-left">Job</th>
                  <th className="px-4 py-3 text-left">Resume</th>
                  <th className="px-4 py-3 text-left">Status</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {applications.map((a) => {
                  const resume = a.resumeUrl || a.user.jobSeekerProfile?.resumeUrl || "";
                  return (
                    <tr key={a.id}>
                      <td className="px-4 py-3">
                        <div className="font-medium text-neutral-800">{a.user.name}</div>
                        <div className="text-xs text-neutral-500">{a.user.email}</div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="font-medium text-neutral-800">{a.job.title}</div>
                        <div className="text-xs text-neutral-500">{a.job.company || ""}</div>
                      </td>
                      <td className="px-4 py-3">
                        {resume ? <a href={resume} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-blue-600 hover:underline"><FileDown size={14} /> Download</a> : <span className="text-xs text-neutral-400">No resume</span>}
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-flex px-2 py-0.5 text-xs rounded-full bg-neutral-100 text-neutral-700">{a.status}</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex justify-end gap-2">
                          {(["submitted", "viewed", "shortlisted", "rejected"] as const).map((status) => (
                            <button key={status} onClick={() => startTransition(async () => {
                              await updateApplicationStatusAction(a.id, status);
                              show("ok", `Marked ${status}`);
                            })} className="px-2 py-1 text-xs border border-neutral-200 rounded-md hover:border-navy-300">{status}</button>
                          ))}
                          <button onClick={() => startTransition(async () => {
                            if (confirm("Delete this application?")) {
                              await deleteApplicationAction(a.id);
                              show("ok", "Application deleted");
                            }
                          })} className="p-2 text-neutral-400 hover:text-red-600"><Trash2 size={16} /></button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "seekers" && (
        <div>
          <h2 className="text-lg font-semibold text-neutral-800 mb-4">Job Seekers CRM ({seekers.length})</h2>
          <div className="bg-white border border-neutral-200 rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 border-b border-neutral-200">
                <tr>
                  <th className="px-4 py-3 text-left">Seeker</th>
                  <th className="px-4 py-3 text-left">Skills</th>
                  <th className="px-4 py-3 text-left">Applications</th>
                  <th className="px-4 py-3 text-left">Resume</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {seekers.map((s) => (
                  <tr key={s.id}>
                    <td className="px-4 py-3">
                      <div className="font-medium text-neutral-800">{s.name}</div>
                      <div className="text-xs text-neutral-500">{s.email}</div>
                    </td>
                    <td className="px-4 py-3 text-xs text-neutral-600 max-w-xs truncate">{s.jobSeekerProfile?.skills || "-"}</td>
                    <td className="px-4 py-3 text-xs text-neutral-600">{s._count.jobApplications}</td>
                    <td className="px-4 py-3">
                      {s.jobSeekerProfile?.resumeUrl ? <a href={s.jobSeekerProfile.resumeUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-blue-600 hover:underline"><FileDown size={14} /> Download</a> : <span className="text-xs text-neutral-400">No resume</span>}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex justify-end gap-2">
                        <button onClick={() => startTransition(async () => {
                          await toggleUserActiveAction(s.id, !s.isActive);
                          show("ok", s.isActive ? "User deactivated" : "User activated");
                        })} className="p-2 text-neutral-400 hover:text-blue-600">{s.isActive ? <EyeOff size={16} /> : <Eye size={16} />}</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {jobModal && (
        <Modal title={jobModal === "new" ? "Add Job" : "Edit Job"} onClose={() => setJobModal(null)}>
          <div className="grid md:grid-cols-2 gap-4">
            <label className="text-sm">Title<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.title} onChange={(e) => setJobForm({ ...jobForm, title: e.target.value })} /></label>
            <label className="text-sm">Company<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.company} onChange={(e) => setJobForm({ ...jobForm, company: e.target.value })} /></label>
            <label className="text-sm">Location<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.location} onChange={(e) => setJobForm({ ...jobForm, location: e.target.value })} /></label>
            <label className="text-sm">Type<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.jobType} onChange={(e) => setJobForm({ ...jobForm, jobType: e.target.value })} /></label>
            <label className="text-sm">Salary<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.salary} onChange={(e) => setJobForm({ ...jobForm, salary: e.target.value })} /></label>
            <label className="text-sm">Apply Link<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.applyLink} onChange={(e) => setJobForm({ ...jobForm, applyLink: e.target.value })} /></label>
            <label className="text-sm">Source<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={jobForm.source} onChange={(e) => setJobForm({ ...jobForm, source: e.target.value })} /></label>
            <label className="text-sm">Featured
              <select className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={String(jobForm.isFeatured)} onChange={(e) => setJobForm({ ...jobForm, isFeatured: e.target.value === "true" })}>
                <option value="false">No</option>
                <option value="true">Yes</option>
              </select>
            </label>
            <label className="text-sm">Active
              <select className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={String(jobForm.isActive)} onChange={(e) => setJobForm({ ...jobForm, isActive: e.target.value === "true" })}>
                <option value="true">Yes</option>
                <option value="false">No</option>
              </select>
            </label>
          </div>
          <label className="text-sm block mt-4">Description<textarea className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" rows={5} value={jobForm.description} onChange={(e) => setJobForm({ ...jobForm, description: e.target.value })} /></label>
          <div className="flex justify-end gap-3 mt-5">
            <button className="px-4 py-2 text-sm" onClick={() => setJobModal(null)}>Cancel</button>
            <button disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm rounded-lg" onClick={saveJob}>{isPending ? <Loader2 size={14} className="animate-spin" /> : "Save"}</button>
          </div>
        </Modal>
      )}

      {slideModal && (
        <Modal title={slideModal === "new" ? "Add Jobs Slide" : "Edit Jobs Slide"} onClose={() => setSlideModal(null)}>
          <div className="grid md:grid-cols-2 gap-4">
            <label className="text-sm md:col-span-2">Image URL<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={slideForm.imageUrl} onChange={(e) => setSlideForm({ ...slideForm, imageUrl: e.target.value })} /></label>
            <label className="text-sm md:col-span-2">Or Upload Image<input type="file" accept="image/*" className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" onChange={(e) => setSlideFile(e.target.files?.[0] ?? null)} /></label>
            <label className="text-sm">Label<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={slideForm.label} onChange={(e) => setSlideForm({ ...slideForm, label: e.target.value })} /></label>
            <label className="text-sm">Title<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={slideForm.title} onChange={(e) => setSlideForm({ ...slideForm, title: e.target.value })} /></label>
            <label className="text-sm md:col-span-2">Subtitle<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={slideForm.subtitle} onChange={(e) => setSlideForm({ ...slideForm, subtitle: e.target.value })} /></label>
            <label className="text-sm">Sort Order<input type="number" className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={slideForm.sortOrder} onChange={(e) => setSlideForm({ ...slideForm, sortOrder: Number(e.target.value) || 0 })} /></label>
            <label className="text-sm">Active
              <select className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={String(slideForm.isActive)} onChange={(e) => setSlideForm({ ...slideForm, isActive: e.target.value === "true" })}>
                <option value="true">Yes</option>
                <option value="false">No</option>
              </select>
            </label>
          </div>
          <div className="flex justify-end gap-3 mt-5">
            <button className="px-4 py-2 text-sm" onClick={() => setSlideModal(null)}>Cancel</button>
            <button disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm rounded-lg" onClick={saveSlide}>{isPending ? <Loader2 size={14} className="animate-spin" /> : "Save"}</button>
          </div>
        </Modal>
      )}

      {sourceModal && (
        <Modal title={sourceModal === "new" ? "Add API Source" : "Edit API Source"} onClose={() => setSourceModal(null)}>
          <div className="grid md:grid-cols-2 gap-4">
            <label className="text-sm">Name<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.name} onChange={(e) => setSourceForm({ ...sourceForm, name: e.target.value })} /></label>
            <label className="text-sm">Source Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.sourceKey} onChange={(e) => setSourceForm({ ...sourceForm, sourceKey: e.target.value })} /></label>
            <label className="text-sm md:col-span-2">Endpoint<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.endpoint} onChange={(e) => setSourceForm({ ...sourceForm, endpoint: e.target.value })} /></label>
            <label className="text-sm">Auth Header<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.authHeader} onChange={(e) => setSourceForm({ ...sourceForm, authHeader: e.target.value })} /></label>
            <label className="text-sm">Auth Token<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.authToken} onChange={(e) => setSourceForm({ ...sourceForm, authToken: e.target.value })} /></label>
            <label className="text-sm">Jobs Path<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.jobPath} onChange={(e) => setSourceForm({ ...sourceForm, jobPath: e.target.value })} /></label>
            <label className="text-sm">Title Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.titleKey} onChange={(e) => setSourceForm({ ...sourceForm, titleKey: e.target.value })} /></label>
            <label className="text-sm">Company Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.companyKey} onChange={(e) => setSourceForm({ ...sourceForm, companyKey: e.target.value })} /></label>
            <label className="text-sm">Location Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.locationKey} onChange={(e) => setSourceForm({ ...sourceForm, locationKey: e.target.value })} /></label>
            <label className="text-sm">Type Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.typeKey} onChange={(e) => setSourceForm({ ...sourceForm, typeKey: e.target.value })} /></label>
            <label className="text-sm">Salary Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.salaryKey} onChange={(e) => setSourceForm({ ...sourceForm, salaryKey: e.target.value })} /></label>
            <label className="text-sm">Description Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.descriptionKey} onChange={(e) => setSourceForm({ ...sourceForm, descriptionKey: e.target.value })} /></label>
            <label className="text-sm">Apply Link Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.applyLinkKey} onChange={(e) => setSourceForm({ ...sourceForm, applyLinkKey: e.target.value })} /></label>
            <label className="text-sm">PostedAt Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.postedAtKey} onChange={(e) => setSourceForm({ ...sourceForm, postedAtKey: e.target.value })} /></label>
            <label className="text-sm">External ID Key<input className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={sourceForm.externalIdKey} onChange={(e) => setSourceForm({ ...sourceForm, externalIdKey: e.target.value })} /></label>
            <label className="text-sm">Active
              <select className="mt-1 w-full px-3 py-2 border border-neutral-200 rounded-lg" value={String(sourceForm.isActive)} onChange={(e) => setSourceForm({ ...sourceForm, isActive: e.target.value === "true" })}>
                <option value="true">Yes</option>
                <option value="false">No</option>
              </select>
            </label>
          </div>
          <div className="flex justify-end gap-3 mt-5">
            <button className="px-4 py-2 text-sm" onClick={() => setSourceModal(null)}>Cancel</button>
            <button disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm rounded-lg" onClick={saveSource}>{isPending ? <Loader2 size={14} className="animate-spin" /> : "Save"}</button>
          </div>
        </Modal>
      )}
    </div>
  );
}
