/**
 * 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, createMemo, createSignal, onMount } from "solid-js";
import { BTN_GHOST, BTN_PRIMARY, CARD, INPUT } from "~/components/DashboardShell";
import { ROLE_PREFIXES, type RoleKey } from "./RoleDashboardShared";

const API = "";

type Props = { roleKey: RoleKey };

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

type SortKey = "newest" | "budget_desc" | "budget_asc" | "title_asc";

function readTags(row: MarketplaceItem): string[] {
  const raw = (row as any)?.tags ?? (row as any)?.requirement_tags ?? (row as any)?.skills;
  if (!Array.isArray(raw)) return [];
  return raw.map((item: any) => String(item || "").trim()).filter(Boolean);
}

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 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 [search, setSearch] = createSignal("");
  const [sortBy, setSortBy] = createSignal<SortKey>("newest");
  const [activeTag, setActiveTag] = createSignal("");
  const prefix = () => ROLE_PREFIXES[props.roleKey];

  const allTags = createMemo(() => {
    const tags = new Set<string>();
    for (const row of rows()) {
      for (const tag of readTags(row)) tags.add(tag);
    }
    return Array.from(tags).sort((a, b) => a.localeCompare(b));
  });

  const filteredSortedRows = createMemo(() => {
    const q = search().trim().toLowerCase();
    const tag = activeTag().trim().toLowerCase();
    const next = rows().filter((row) => {
      const tags = readTags(row);
      const matchesTag = !tag || tags.some((t) => t.toLowerCase() === tag);
      if (!matchesTag) return false;
      if (!q) return true;
      return (
        String(row.title || "").toLowerCase().includes(q) ||
        String(row.location || "").toLowerCase().includes(q) ||
        String(row.profession_key || "").toLowerCase().includes(q) ||
        String(row.description || "").toLowerCase().includes(q) ||
        tags.some((t) => t.toLowerCase().includes(q))
      );
    });

    next.sort((a, b) => {
      if (sortBy() === "budget_desc") return Number(b.budget || 0) - Number(a.budget || 0);
      if (sortBy() === "budget_asc") return Number(a.budget || 0) - Number(b.budget || 0);
      if (sortBy() === "title_asc") return String(a.title || "").localeCompare(String(b.title || ""));
      return new Date(String(b.created_at || 0)).getTime() - new Date(String(a.created_at || 0)).getTime();
    });
    return next;
  });

  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": "18px", "font-weight": "800", color: "#111827" }}>
          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",
            gap: "10px",
            "flex-wrap": "wrap",
          }}
        >
          <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>

        <div style={{ display: "grid", gap: "10px", "margin-bottom": "12px" }}>
          <div style={{ display: "grid", "grid-template-columns": "1fr 180px", gap: "10px" }}>
            <input
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              style={INPUT}
              placeholder="Search by title, location, description, tags"
            />
            <select value={sortBy()} onChange={(e) => setSortBy(e.currentTarget.value as SortKey)} style={INPUT}>
              <option value="newest">Sort: Newest</option>
              <option value="budget_desc">Budget High to Low</option>
              <option value="budget_asc">Budget Low to High</option>
              <option value="title_asc">Title A-Z</option>
            </select>
          </div>
          <Show when={allTags().length > 0}>
            <div style={{ display: "flex", gap: "6px", "flex-wrap": "wrap" }}>
              <button
                type="button"
                onClick={() => setActiveTag("")}
                style={{ ...BTN_GHOST, height: "28px", padding: "0 10px", "font-size": "11px", ...(activeTag() ? {} : { border: "1px solid #0D0D2A", color: "#0D0D2A" }) }}
              >
                All Tags
              </button>
              <For each={allTags()}>
                {(tag) => (
                  <button
                    type="button"
                    onClick={() => setActiveTag(tag)}
                    style={{ ...BTN_GHOST, height: "28px", padding: "0 10px", "font-size": "11px", ...(activeTag() === tag ? { border: "1px solid #0D0D2A", color: "#0D0D2A" } : {}) }}
                  >
                    {tag}
                  </button>
                )}
              </For>
            </div>
          </Show>
        </div>

        <Show when={loading()}>
          <p style={{ margin: "0", color: "#9CA3AF", "font-size": "13px" }}>Loading leads...</p>
        </Show>
        <Show when={!loading() && filteredSortedRows().length === 0}>
          <p style={{ margin: "0", color: "#6B7280", "font-size": "13px" }}>
            No leads available right now.
          </p>
        </Show>
        <Show when={!loading() && filteredSortedRows().length > 0}>
          <div style={{ border: "1px solid #E5E7EB", "border-radius": "12px", overflow: "hidden" }}>
            <div style={{ display: "grid", "grid-template-columns": "2fr 1fr 1fr 1fr auto", gap: "8px", padding: "10px 12px", background: "#F9FAFB", "font-size": "11px", "font-weight": "700", color: "#6B7280", "text-transform": "uppercase" }}>
              <span>Requirement</span>
              <span>Location</span>
              <span>Budget</span>
              <span>Tags</span>
              <span style={{ "text-align": "right" }}>Action</span>
            </div>
            <For each={filteredSortedRows()}>
              {(row) => (
                <div
                  style={{
                    display: "grid",
                    "grid-template-columns": "2fr 1fr 1fr 1fr auto",
                    gap: "8px",
                    padding: "12px",
                    background: "white",
                    "border-top": "1px solid #F3F4F6",
                    "align-items": "start",
                  }}
                >
                  <div>
                    <p style={{ margin: "0", "font-size": "13px", "font-weight": "800", color: "#111827" }}>
                      {row.title || "Requirement"}
                    </p>
                    <p style={{ margin: "4px 0 0", "font-size": "12px", color: "#6B7280", "line-height": "1.4" }}>
                      {row.description || "No additional details."}
                    </p>
                  </div>
                  <div style={{ "font-size": "12px", color: "#374151" }}>
                    {row.location || "Location not set"}
                  </div>
                  <div style={{ "font-size": "12px", "font-weight": "700", color: "#111827" }}>
                    {row.budget ? `₹${row.budget}` : "Budget N/A"}
                  </div>
                  <div style={{ display: "flex", gap: "4px", "flex-wrap": "wrap" }}>
                    <For each={readTags(row).slice(0, 3)}>
                      {(tag) => (
                        <span style={{ height: "22px", display: "inline-flex", "align-items": "center", padding: "0 8px", "border-radius": "999px", border: "1px solid #E5E7EB", background: "#F9FAFB", "font-size": "11px", color: "#374151" }}>{tag}</span>
                      )}
                    </For>
                  </div>
                  <div style={{ display: "flex", "justify-content": "flex-end" }}>
                    <button
                      type="button"
                      onClick={() => requestLead(row.id)}
                      disabled={busyId() === row.id}
                      style={{
                        ...BTN_PRIMARY,
                        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>
  );
}
