/**
 * Professional Leads Page - Wired to real backend APIs
 * Endpoints:
 *   GET /api/{profession}/marketplace - List available leads
 *   POST /api/{profession}/leads/request - Request a lead
 * Professions: photographers, makeup-artists, tutors, developers, etc.
 */
import { For, Show, createSignal, onMount } from "solid-js";
import { BTN_GHOST, BTN_ORANGE, CARD } from "~/components/DashboardShell";
import { ROLE_PREFIXES, type RoleKey } from "./RoleDashboardShared";

const API = "/api/gateway";

type Props = { roleKey: RoleKey };

type MarketplaceItem = {
  id: string;
  title?: string;
  location?: string;
  budget?: number | null;
  profession_key?: string;
  description?: string | null;
};

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

export default function ProfessionalLeadsPage(props: Props) {
  const [rows, setRows] = createSignal<MarketplaceItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [busyId, setBusyId] = createSignal<string | null>(null);
  const [msg, setMsg] = createSignal("");
  const [err, setErr] = createSignal("");
  const prefix = () => ROLE_PREFIXES[props.roleKey];

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

  onMount(loadRows);

  const requestLead = async (requirementId: string) => {
    setBusyId(requirementId);
    setMsg("");
    setErr("");
    try {
      const res = await apiFetch(`/api/${prefix()}/leads/request`, {
        method: "POST",
        body: JSON.stringify({ requirement_id: requirementId }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || "Failed to request lead.");
        return;
      }
      setMsg("Lead request submitted to verification and approval flow.");
    } catch {
      setErr("Network error while requesting lead.");
    } finally {
      setBusyId(null);
    }
  };

  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" }}>
          Leads
        </p>
        <p style={{ margin: "4px 0 0", "font-size": "13px", color: "#6B7280" }}>
          Browse open requirements from customers and request contact access.
        </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}>
        <div
          style={{
            display: "flex",
            "justify-content": "space-between",
            "align-items": "center",
            "margin-bottom": "10px",
          }}
        >
          <p style={{ margin: "0", "font-size": "16px", "font-weight": "700", color: "#111827" }}>
            Open Marketplace Leads
          </p>
          <button type="button" onClick={loadRows} style={BTN_GHOST}>
            Refresh
          </button>
        </div>

        <Show when={loading()}>
          <p style={{ margin: "0", color: "#9CA3AF", "font-size": "13px" }}>Loading leads...</p>
        </Show>
        <Show when={!loading() && rows().length === 0}>
          <p style={{ margin: "0", color: "#6B7280", "font-size": "13px" }}>
            No leads available right now.
          </p>
        </Show>
        <Show when={!loading() && rows().length > 0}>
          <div style={{ display: "grid", gap: "10px" }}>
            <For each={rows()}>
              {(row) => (
                <div
                  style={{
                    border: "1px solid #E5E7EB",
                    "border-radius": "12px",
                    padding: "12px",
                    background: "#FCFCFD",
                  }}
                >
                  <div
                    style={{
                      display: "flex",
                      "justify-content": "space-between",
                      gap: "10px",
                      "flex-wrap": "wrap",
                    }}
                  >
                    <div>
                      <p
                        style={{
                          margin: "0",
                          "font-size": "14px",
                          "font-weight": "800",
                          color: "#111827",
                        }}
                      >
                        {row.title || "Requirement"}
                      </p>
                      <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280" }}>
                        {row.location || "Location not set"}{" "}
                        {row.profession_key ? `• ${row.profession_key}` : ""}
                      </p>
                    </div>
                    <span
                      style={{
                        display: "inline-flex",
                        height: "24px",
                        "align-items": "center",
                        padding: "0 10px",
                        "border-radius": "999px",
                        background: "#FFF1EB",
                        color: "#C2410C",
                        "font-size": "11px",
                        "font-weight": "700",
                      }}
                    >
                      {row.budget ? `₹${row.budget}` : "Budget N/A"}
                    </span>
                  </div>
                  <p style={{ margin: "8px 0 0", "font-size": "13px", color: "#374151" }}>
                    {row.description || "No additional details."}
                  </p>
                  <div
                    style={{ display: "flex", "justify-content": "flex-end", "margin-top": "10px" }}
                  >
                    <button
                      type="button"
                      onClick={() => requestLead(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 ? "Requesting..." : "Request Contact"}
                    </button>
                  </div>
                </div>
              )}
            </For>
          </div>
        </Show>
      </div>
    </div>
  );
}
