/**
 * Job Seeker Jobs Page - Wired to real backend APIs
 * Endpoints:
 *   GET /api/jobseeker/jobs - List available jobs from companies
 *   POST /api/jobseeker/jobs/:id/apply - Apply for a job
 *   Custom data: saved_jobs - Bookmarked jobs stored in profile
 */
import { For, Show, createSignal, onMount } from "solid-js";
import { BTN_GHOST, BTN_ORANGE, CARD, INPUT } from "~/components/DashboardShell";
import { readJobSeekerProfile, updateJobSeekerCustomData } from "~/lib/job-seeker-custom-data";

const API = "/api/gateway";

type JobItem = {
  id: string;
  title?: string;
  company_name?: string;
  location?: string;
  salary_min?: number | null;
  salary_max?: number | null;
  employment_type?: string;
  status?: string;
  description?: string | null;
};

type SavedJob = {
  id: string;
  title: string;
  company?: string;
  location?: string;
  salary?: string;
  saved_at: string;
};

async function apiFetch(path: string, opts?: RequestInit) {
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: { "Content-Type": "application/json", ...(opts?.headers ?? {}) },
  });
}

function formatSalary(job: JobItem): string {
  const min = Number(job.salary_min || 0);
  const max = Number(job.salary_max || 0);
  if (!min && !max) return "";
  if (min && max) return `${min} - ${max}`;
  return String(min || max || "");
}

function toSavedJobs(value: unknown): SavedJob[] {
  if (!Array.isArray(value)) return [];
  return value
    .map((item) => {
      const row = item as Record<string, unknown>;
      const id = String(row?.id || "").trim();
      if (!id) return null;
      return {
        id,
        title: String(row?.title || "Untitled Job"),
        company: String(row?.company || row?.company_name || ""),
        location: String(row?.location || ""),
        salary: String(row?.salary || ""),
        saved_at: String(row?.saved_at || new Date().toISOString()),
      };
    })
    .filter(Boolean) as SavedJob[];
}

export default function JobSeekerJobsPage() {
  const [rows, setRows] = createSignal<JobItem[]>([]);
  const [savedJobs, setSavedJobs] = createSignal<SavedJob[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [busyId, setBusyId] = createSignal<string | null>(null);
  const [search, setSearch] = createSignal("");
  const [msg, setMsg] = createSignal("");
  const [err, setErr] = createSignal("");

  const loadRows = async () => {
    setLoading(true);
    setErr("");
    try {
      const res = await apiFetch("/api/jobseeker/jobs?page=1&limit=100");
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || "Failed to load jobs.");
        setRows([]);
        return;
      }
      setRows(Array.isArray(data?.data) ? data.data : []);
    } catch {
      setErr("Network error while loading jobs.");
      setRows([]);
    } finally {
      setLoading(false);
    }
  };

  const loadSavedJobs = async () => {
    try {
      const profile = await readJobSeekerProfile();
      setSavedJobs(toSavedJobs(profile?.custom_data?.saved_jobs));
    } catch {
      // non-blocking
      setSavedJobs([]);
    }
  };

  onMount(() => {
    void loadRows();
    void loadSavedJobs();
  });

  const applyJob = async (jobId: string) => {
    setBusyId(jobId);
    setMsg("");
    setErr("");
    try {
      const res = await apiFetch(`/api/jobseeker/jobs/${jobId}/apply`, {
        method: "POST",
        body: JSON.stringify({}),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || "Failed to apply for job.");
        return;
      }
      setMsg("Application submitted successfully.");
    } catch {
      setErr("Network error while applying.");
    } finally {
      setBusyId(null);
    }
  };

  const isSaved = (jobId: string) => savedJobs().some((row) => row.id === jobId);

  const toggleSave = async (job: JobItem) => {
    setBusyId(job.id);
    setMsg("");
    setErr("");
    const existing = savedJobs();
    const next = isSaved(job.id)
      ? existing.filter((row) => row.id !== job.id)
      : [
          ...existing,
          {
            id: job.id,
            title: String(job.title || "Untitled Job"),
            company: String(job.company_name || ""),
            location: String(job.location || ""),
            salary: formatSalary(job),
            saved_at: new Date().toISOString(),
          },
        ];
    try {
      await updateJobSeekerCustomData((current) => ({ ...current, saved_jobs: next }));
      setSavedJobs(next);
      setMsg(isSaved(job.id) ? "Job removed from saved list." : "Job saved for later.");
    } catch (e: any) {
      setErr(e?.message || "Failed to update saved jobs.");
    } finally {
      setBusyId(null);
    }
  };

  const filtered = () => {
    const q = search().trim().toLowerCase();
    if (!q) return rows();
    return rows().filter(
      (r) =>
        String(r.title || "")
          .toLowerCase()
          .includes(q) ||
        String(r.company_name || "")
          .toLowerCase()
          .includes(q) ||
        String(r.location || "")
          .toLowerCase()
          .includes(q)
    );
  };

  return (
    <div style={{ display: "grid", gap: "14px", "max-width": "980px" }}>
      <div style={CARD}>
        <p style={{ margin: "0", "font-size": "22px", "font-weight": "800", color: "#0D0D2A" }}>
          Jobs
        </p>
        <p style={{ margin: "4px 0 0", "font-size": "13px", color: "#6B7280" }}>
          Explore approved job postings and apply directly.
        </p>
      </div>

      <Show when={msg()}>
        <div
          style={{
            ...CARD,
            border: "1px solid #BBF7D0",
            background: "#ECFDF5",
            padding: "12px 14px",
            color: "#065F46",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {msg()}
        </div>
      </Show>
      <Show when={err()}>
        <div
          style={{
            ...CARD,
            border: "1px solid #FECACA",
            background: "#FEF2F2",
            padding: "12px 14px",
            color: "#B91C1C",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {err()}
        </div>
      </Show>

      <div style={{ ...CARD, display: "flex", gap: "10px", "align-items": "center" }}>
        <input
          value={search()}
          onInput={(e) => setSearch(e.currentTarget.value)}
          style={INPUT}
          placeholder="Search jobs, company, location"
        />
        <button type="button" onClick={loadRows} style={BTN_GHOST}>
          Refresh
        </button>
      </div>

      <Show when={loading()}>
        <div style={{ ...CARD, "text-align": "center", color: "#9CA3AF" }}>Loading jobs...</div>
      </Show>
      <Show when={!loading() && filtered().length === 0}>
        <div style={{ ...CARD, "text-align": "center", color: "#6B7280" }}>No jobs found.</div>
      </Show>

      <Show when={!loading() && filtered().length > 0}>
        <div style={{ display: "grid", gap: "10px" }}>
          <For each={filtered()}>
            {(row) => (
              <div style={{ ...CARD, padding: "14px" }}>
                <div
                  style={{
                    display: "flex",
                    "justify-content": "space-between",
                    gap: "10px",
                    "flex-wrap": "wrap",
                  }}
                >
                  <div>
                    <p
                      style={{
                        margin: "0",
                        "font-size": "16px",
                        "font-weight": "800",
                        color: "#111827",
                      }}
                    >
                      {row.title || "Untitled Job"}
                    </p>
                    <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                      {row.company_name || "Company"} {row.location ? `• ${row.location}` : ""}{" "}
                      {row.employment_type ? `• ${row.employment_type}` : ""}
                    </p>
                  </div>
                  <span
                    style={{
                      display: "inline-flex",
                      height: "24px",
                      "align-items": "center",
                      padding: "0 10px",
                      "border-radius": "999px",
                      background: "#EEF2FF",
                      color: "#3730A3",
                      "font-size": "11px",
                      "font-weight": "700",
                    }}
                  >
                    {String(row.status || "OPEN").replace(/_/g, " ")}
                  </span>
                </div>
                <p style={{ margin: "8px 0 0", "font-size": "13px", color: "#374151" }}>
                  {row.description || "No description provided."}
                </p>
                <p
                  style={{
                    margin: "8px 0 0",
                    "font-size": "12px",
                    color: "#111827",
                    "font-weight": "700",
                  }}
                >
                  Salary: {formatSalary(row) || "Not specified"}
                </p>
                <div
                  style={{
                    display: "flex",
                    "justify-content": "flex-end",
                    gap: "8px",
                    "margin-top": "10px",
                  }}
                >
                  <button
                    type="button"
                    onClick={() => void toggleSave(row)}
                    disabled={busyId() === row.id}
                    style={{
                      ...BTN_GHOST,
                      height: "32px",
                      "font-size": "12px",
                      padding: "0 12px",
                      opacity: busyId() === row.id ? "0.7" : "1",
                    }}
                  >
                    {busyId() === row.id ? "Updating..." : isSaved(row.id) ? "Unsave" : "Save"}
                  </button>
                  <button
                    type="button"
                    onClick={() => applyJob(row.id)}
                    disabled={busyId() === row.id}
                    style={{
                      ...BTN_ORANGE,
                      height: "32px",
                      "font-size": "12px",
                      padding: "0 12px",
                      opacity: busyId() === row.id ? "0.7" : "1",
                    }}
                  >
                    {busyId() === row.id ? "Applying..." : "Apply"}
                  </button>
                </div>
              </div>
            )}
          </For>
        </div>
      </Show>
    </div>
  );
}
