/**
 * Company Applications Page - Wired to real backend APIs
 * Endpoints:
 *   GET /api/companies/jobs - List company's jobs
 *   GET /api/companies/jobs/:id/applications - Get applications for a job
 *   POST /api/companies/applications/:id/contact - Unlock contact info
 *   PATCH /api/companies/applications/:id/status - Update application status
 */
import { For, Show, createSignal, onMount } from "solid-js";
import { BTN_GHOST, BTN_ORANGE, CARD, INPUT, LABEL } from "~/components/DashboardShell";

const API = "";

interface JobItem {
  id: string;
  title: string;
  status: string;
}

interface ApplicationItem {
  id: string;
  job_id: string;
  applicant_user_id: string;
  status: string;
  cover_note?: string | null;
  resume_url?: string | null;
  applied_at?: string;
  reference_number: string;
  // Profile snapshot — contact fields excluded by backend
  applicant_name?: string | null;
  avatar_url?: string | null;
  headline?: string | null;
  skills?: string | null;
  education?: string | null;
  work_experience?: string | null;
  summary?: string | null;
}

interface ContactInfo {
  full_name?: string | null;
  email?: string | null;
  phone?: string | null;
  quota?: {
    total_remaining: number;
  };
}

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

export default function CompanyApplicationsPage() {
  const [jobs, setJobs] = createSignal<JobItem[]>([]);
  const [selectedJobId, setSelectedJobId] = createSignal("");
  const [applications, setApplications] = createSignal<ApplicationItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [loadingApps, setLoadingApps] = createSignal(false);
  const [statusFilter, setStatusFilter] = createSignal("");
  const [actionMsg, setActionMsg] = createSignal("");
  const [busyAppId, setBusyAppId] = createSignal<string | null>(null);
  const [contactByApp, setContactByApp] = createSignal<Record<string, ContactInfo>>({});

  const loadJobs = async () => {
    setLoading(true);
    try {
      const res = await apiFetch("/api/companies/jobs?page=1&limit=100");
      if (!res.ok) {
        setJobs([]);
        return;
      }
      const payload = await res.json().catch(() => ({}));
      const list = Array.isArray(payload?.data) ? payload.data : [];
      setJobs(list);
      if (list.length > 0) {
        const nextJobId = selectedJobId() || list[0].id;
        setSelectedJobId(nextJobId);
        await loadApplications(nextJobId, statusFilter());
      } else {
        setSelectedJobId("");
        setApplications([]);
      }
    } finally {
      setLoading(false);
    }
  };

  const loadApplications = async (jobId: string, status?: string) => {
    if (!jobId) {
      setApplications([]);
      return;
    }
    setLoadingApps(true);
    try {
      const query = new URLSearchParams();
      query.set("page", "1");
      query.set("limit", "50");
      if (status) query.set("status", status);
      const res = await apiFetch(`/api/companies/jobs/${jobId}/applications?${query.toString()}`);
      if (!res.ok) {
        setApplications([]);
        return;
      }
      const payload = await res.json().catch(() => ({}));
      setApplications(Array.isArray(payload?.data) ? payload.data : []);
    } finally {
      setLoadingApps(false);
    }
  };

  onMount(async () => {
    await loadJobs();
  });

  const refreshCurrent = async () => {
    await loadApplications(selectedJobId(), statusFilter());
  };

  const updateApplicationStatus = async (id: string, status: string) => {
    setBusyAppId(id);
    setActionMsg("");
    try {
      const res = await apiFetch(`/api/companies/applications/${id}/status`, {
        method: "PATCH",
        body: JSON.stringify({ status }),
      });
      if (res.ok) {
        setActionMsg(`Application marked as ${status.replace(/_/g, " ")}.`);
        await refreshCurrent();
      } else {
        const data = await res.json().catch(() => ({}));
        setActionMsg(data.error ?? data.message ?? "Failed to update application status.");
      }
    } finally {
      setBusyAppId(null);
    }
  };

  const loadContact = async (id: string) => {
    setBusyAppId(id);
    setActionMsg("");
    try {
      const res = await apiFetch(`/api/companies/applications/${id}/contact`, { method: "POST" });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setContactByApp((prev) => ({ ...prev, [id]: data }));
      } else {
        setActionMsg(data.error ?? data.message ?? "Failed to load contact details.");
      }
    } finally {
      setBusyAppId(null);
    }
  };

  const prettyDate = (value?: string) => {
    if (!value) return "—";
    const d = new Date(value);
    return Number.isNaN(d.getTime()) ? value : d.toLocaleString("en-IN");
  };

  return (
    <div style={{ "max-width": "920px" }}>
      <div
        style={{
          display: "flex",
          "justify-content": "space-between",
          "align-items": "center",
          "margin-bottom": "16px",
          gap: "12px",
          "flex-wrap": "wrap",
        }}
      >
        <div>
          <p style={{ margin: "0", "font-size": "18px", "font-weight": "800", color: "#111827" }}>
            Applications
          </p>
          <p style={{ margin: "4px 0 0", "font-size": "13px", color: "#6B7280" }}>
            Review applicants and update their hiring stage.
          </p>
        </div>
        <button type="button" onClick={refreshCurrent} style={BTN_GHOST}>
          Refresh
        </button>
      </div>

      <Show when={actionMsg()}>
        <div
          style={{
            ...CARD,
            "margin-bottom": "14px",
            padding: "12px 14px",
            "font-size": "13px",
            color: "#374151",
          }}
        >
          {actionMsg()}
        </div>
      </Show>

      <Show when={loading()}>
        <div style={{ ...CARD, "text-align": "center", color: "#9CA3AF" }}>Loading jobs…</div>
      </Show>

      <Show when={!loading()}>
        <div
          style={{
            ...CARD,
            "margin-bottom": "12px",
            display: "grid",
            "grid-template-columns": "1fr 1fr",
            gap: "12px",
          }}
        >
          <div>
            <label style={LABEL}>Select Job</label>
            <select
              value={selectedJobId()}
              onChange={(e) => {
                const next = e.currentTarget.value;
                setSelectedJobId(next);
                loadApplications(next, statusFilter());
              }}
              style={INPUT}
            >
              <Show when={jobs().length === 0}>
                <option value="">No jobs available</option>
              </Show>
              <For each={jobs()}>
                {(job) => (
                  <option value={job.id}>
                    {job.title} ({job.status.replace(/_/g, " ")})
                  </option>
                )}
              </For>
            </select>
          </div>
          <div>
            <label style={LABEL}>Filter by Status</label>
            <select
              value={statusFilter()}
              onChange={(e) => {
                const next = e.currentTarget.value;
                setStatusFilter(next);
                loadApplications(selectedJobId(), next);
              }}
              style={INPUT}
            >
              <option value="">All Statuses</option>
              <option value="APPLIED">Applied</option>
              <option value="SHORTLISTED">Shortlisted</option>
              <option value="INTERVIEW">Interview</option>
              <option value="OFFERED">Offered</option>
              <option value="HIRED">Hired</option>
              <option value="REJECTED">Rejected</option>
              <option value="WITHDRAWN">Withdrawn</option>
            </select>
          </div>
        </div>

        <Show when={!selectedJobId()}>
          <div style={{ ...CARD, "text-align": "center", color: "#9CA3AF" }}>
            Create a job first to view applications.
          </div>
        </Show>
      </Show>

      <Show when={loadingApps()}>
        <div style={{ ...CARD, "text-align": "center", color: "#9CA3AF" }}>
          Loading applications…
        </div>
      </Show>

      <Show when={!loadingApps() && selectedJobId() && applications().length === 0}>
        <div style={{ ...CARD, "text-align": "center", color: "#6B7280" }}>
          No applications found for this job.
        </div>
      </Show>

      <Show when={!loadingApps() && applications().length > 0}>
        <div style={{ display: "grid", gap: "10px" }}>
          <For each={applications()}>
            {(app) => (
              <div style={{ ...CARD, padding: "16px" }}>
                {/* Header row: name + status */}
                <div style={{ display: "flex", "justify-content": "space-between", "align-items": "flex-start", gap: "10px", "flex-wrap": "wrap" }}>
                  <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                    <Show
                      when={app.avatar_url}
                      fallback={
                        <div style={{ width: "40px", height: "40px", "border-radius": "50%", background: "#F3F4F6", display: "flex", "align-items": "center", "justify-content": "center", "font-size": "18px", "flex-shrink": "0" }}>👤</div>
                      }
                    >
                      <img src={app.avatar_url!} alt="Applicant" style={{ width: "40px", height: "40px", "border-radius": "50%", "object-fit": "cover", "flex-shrink": "0", border: "1px solid #E5E7EB" }} />
                    </Show>
                    <div>
                      <p style={{ margin: "0", "font-size": "14px", "font-weight": "800", color: "#111827" }}>
                        {app.applicant_name || app.reference_number}
                      </p>
                      <Show when={app.headline}>
                        <p style={{ margin: "2px 0 0", "font-size": "12px", color: "#6B7280" }}>{app.headline}</p>
                      </Show>
                      <p style={{ margin: "2px 0 0", "font-size": "11px", color: "#9CA3AF" }}>Applied {prettyDate(app.applied_at)}</p>
                    </div>
                  </div>
                  <span style={{ display: "inline-flex", "align-items": "center", height: "24px", padding: "0 10px", "border-radius": "999px", background: "#EEF2FF", color: "#3730A3", "font-size": "11px", "font-weight": "700" }}>
                    {app.status.replace(/_/g, " ")}
                  </span>
                </div>

                {/* Cover note */}
                <Show when={app.cover_note}>
                  <p style={{ margin: "10px 0 0", "font-size": "13px", color: "#374151", "line-height": "1.55", "border-left": "2px solid #FF5E13", "padding-left": "10px" }}>
                    {app.cover_note}
                  </p>
                </Show>

                {/* Profile snapshot */}
                <Show when={app.summary || app.skills || app.education || app.work_experience}>
                  <div style={{ "margin-top": "12px", display: "grid", gap: "8px" }}>
                    <Show when={app.summary}>
                      <div>
                        <p style={{ margin: "0 0 2px", "font-size": "10px", "font-weight": "700", color: "#9CA3AF", "letter-spacing": "0.05em" }}>SUMMARY</p>
                        <p style={{ margin: "0", "font-size": "12px", color: "#374151", "line-height": "1.55" }}>{app.summary}</p>
                      </div>
                    </Show>
                    <Show when={app.skills}>
                      <div>
                        <p style={{ margin: "0 0 2px", "font-size": "10px", "font-weight": "700", color: "#9CA3AF", "letter-spacing": "0.05em" }}>SKILLS</p>
                        <p style={{ margin: "0", "font-size": "12px", color: "#374151" }}>{app.skills}</p>
                      </div>
                    </Show>
                    <Show when={app.education}>
                      <div>
                        <p style={{ margin: "0 0 2px", "font-size": "10px", "font-weight": "700", color: "#9CA3AF", "letter-spacing": "0.05em" }}>EDUCATION</p>
                        <p style={{ margin: "0", "font-size": "12px", color: "#374151", "white-space": "pre-line" }}>{app.education}</p>
                      </div>
                    </Show>
                    <Show when={app.work_experience}>
                      <div>
                        <p style={{ margin: "0 0 2px", "font-size": "10px", "font-weight": "700", color: "#9CA3AF", "letter-spacing": "0.05em" }}>WORK EXPERIENCE</p>
                        <p style={{ margin: "0", "font-size": "12px", color: "#374151", "white-space": "pre-line" }}>{app.work_experience}</p>
                      </div>
                    </Show>
                  </div>
                </Show>

                {/* Resume download */}
                <Show when={app.resume_url}>
                  <div style={{ "margin-top": "10px" }}>
                    <a
                      href={app.resume_url!}
                      target="_blank"
                      rel="noreferrer"
                      style={{ display: "inline-flex", "align-items": "center", gap: "4px", "font-size": "12px", "font-weight": "700", color: "#1D4ED8", "text-decoration": "none", padding: "4px 10px", background: "#EFF6FF", "border-radius": "6px", border: "1px solid #BFDBFE" }}
                    >
                      📄 Download Resume PDF
                    </a>
                  </div>
                </Show>

                <div
                  style={{ display: "flex", gap: "8px", "flex-wrap": "wrap", "margin-top": "12px" }}
                >
                  <button
                    type="button"
                    onClick={() => updateApplicationStatus(app.id, "SHORTLISTED")}
                    disabled={busyAppId() === app.id}
                    style={{ ...BTN_GHOST, height: "32px", "font-size": "12px", padding: "0 12px" }}
                  >
                    Shortlist
                  </button>
                  <button
                    type="button"
                    onClick={() => updateApplicationStatus(app.id, "INTERVIEW")}
                    disabled={busyAppId() === app.id}
                    style={{ ...BTN_GHOST, height: "32px", "font-size": "12px", padding: "0 12px" }}
                  >
                    Interview
                  </button>
                  <button
                    type="button"
                    onClick={() => updateApplicationStatus(app.id, "OFFERED")}
                    disabled={busyAppId() === app.id}
                    style={{ ...BTN_GHOST, height: "32px", "font-size": "12px", padding: "0 12px" }}
                  >
                    Offer
                  </button>
                  <button
                    type="button"
                    onClick={() => updateApplicationStatus(app.id, "HIRED")}
                    disabled={busyAppId() === app.id}
                    style={{
                      ...BTN_ORANGE,
                      height: "32px",
                      "font-size": "12px",
                      padding: "0 12px",
                    }}
                  >
                    Hire
                  </button>
                  <button
                    type="button"
                    onClick={() => updateApplicationStatus(app.id, "REJECTED")}
                    disabled={busyAppId() === app.id}
                    style={{ ...BTN_GHOST, height: "32px", "font-size": "12px", padding: "0 12px" }}
                  >
                    Reject
                  </button>
                  <button
                    type="button"
                    onClick={() => loadContact(app.id)}
                    disabled={busyAppId() === app.id}
                    style={{ ...BTN_GHOST, height: "32px", "font-size": "12px", padding: "0 12px" }}
                  >
                    View Contact
                  </button>
                </div>

                <Show when={contactByApp()[app.id]}>
                  <div
                    style={{
                      margin: "12px 0 0",
                      padding: "10px",
                      border: "1px solid #E5E7EB",
                      "border-radius": "8px",
                      background: "#F9FAFB",
                    }}
                  >
                    <p
                      style={{
                        margin: "0",
                        "font-size": "13px",
                        "font-weight": "700",
                        color: "#111827",
                      }}
                    >
                      {contactByApp()[app.id]?.full_name || "Applicant"}
                    </p>
                    <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#4B5563" }}>
                      {contactByApp()[app.id]?.email || "No email"}
                    </p>
                    <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#4B5563" }}>
                      {contactByApp()[app.id]?.phone || "No phone"}
                    </p>
                    <p style={{ margin: "6px 0 0", "font-size": "11px", color: "#6B7280" }}>
                      Remaining contact views: {contactByApp()[app.id]?.quota?.total_remaining ?? 0}
                    </p>
                  </div>
                </Show>
              </div>
            )}
          </For>
        </div>
      </Show>
    </div>
  );
}
