import { useEffect, useState } from "react";
import { useApp } from "../state/store";
import { api } from "../lib/api";
import { wizardApi } from "../lib/wizardApi";
import { curatedPublishedFlows } from "../lib/flowCuration";
import { Branch, Layers, Pulse } from "../components/icons";

export type HubKey = "procurement" | "hr" | "it";

interface HubWorkflow {
  label: string;
  subject: string;
  processHint: string;
}

interface HubSpec {
  title: string;
  workbench: string;
  intro: string;
  match: RegExp;
  workflows: HubWorkflow[];
}

const HUBS: Record<HubKey, HubSpec> = {
  procurement: {
    title: "Procurement workbench",
    workbench: "Purchase requests, vendor approvals, three-way match",
    intro:
      "Everything a store manager needs to buy something — from a laptop to a forklift — and watch it move through the approval chain.",
    match: /procure|purchase|vendor|\bpo\b|\bp2p\b|requisition|payment|invoice/i,
    workflows: [
      { label: "New purchase request", subject: "store-204-laptop", processHint: "procurement" },
      { label: "Vendor approval", subject: "vendor-quote-Q3", processHint: "vendor" },
      { label: "PO change / cancel", subject: "po-change-may", processHint: "po" },
      { label: "Three-way match", subject: "match-batch-mar", processHint: "match" },
    ],
  },
  hr: {
    title: "HR workbench",
    workbench: "Hiring, onboarding, leave, payroll",
    intro:
      "All people movements run here. Start an onboarding for a new hire, file a leave request, or kick off a review cycle.",
    match: /onboard|offboard|leave|\bhr\b|hiring|payroll|employee|people operations/i,
    workflows: [
      { label: "Employee onboarding", subject: "new-hire-2026Q3", processHint: "onboard" },
      { label: "Off-boarding", subject: "leaver-2026Q3", processHint: "offboard" },
      { label: "Sick leave", subject: "sick-leave-may", processHint: "leave" },
      { label: "Payroll management", subject: "payroll-Q3-2026", processHint: "payroll" },
    ],
  },
  it: {
    title: "IT workbench",
    workbench: "Access requests, equipment, service tickets, off-boarding",
    intro:
      "When something breaks, request access, or you need a new account — file it here and route it to the right on-call.",
    match: /\bit\b|ticket|incident|service operations|access request|sap access|laptop request|hardware request|software request|password reset|account provisioning/i,
    workflows: [
      { label: "Access request", subject: "access-sap-RW", processHint: "access" },
      { label: "Equipment request", subject: "store-204-laptop", processHint: "equipment" },
      { label: "Service ticket", subject: "incident-store-204", processHint: "service" },
      { label: "User off-boarding", subject: "user-leaver-jun", processHint: "offboard" },
    ],
  },
};

interface PublishedFlow {
  _key: string;
  display_name: string;
  description?: string;
  name?: string;
}

async function loadPublishedFlows(): Promise<PublishedFlow[]> {
  const res = await fetch(`${api.config.baseUrl}/api/ea2/flow/processes?limit=200`, {
    headers: { Authorization: `Bearer ${sessionStorage.getItem("fm.mc.token.v1")}` },
  });
  if (!res.ok) throw new Error(`processes ${res.status}`);
  const body = await res.json();
  return curatedPublishedFlows((body?.items || []) as any[]).map((it) => ({
    _key: it._key,
    display_name: it.display_name!,
    description: it.description,
    name: it.name,
  }));
}

export default function Hub({ hub }: { hub: HubKey }) {
  const spec = HUBS[hub];
  const pushToast = useApp((s) => s.pushToast);
  const setScene = useApp((s) => s.setScene);
  const [flows, setFlows] = useState<PublishedFlow[] | null>(null);
  const [busy, setBusy] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    loadPublishedFlows()
      .then((rows) => !cancelled && setFlows(rows))
      .catch((err) => !cancelled && pushToast("err", `Catalogue failed: ${err.message}`));
    return () => {
      cancelled = true;
    };
  }, [hub]);

  const matching = (flows || []).filter((f) => spec.match.test(`${f.display_name} ${f.description || ""} ${f.name || ""}`)).slice(0, 8);
  const fallback = (flows || []).slice(0, 6);
  const visible = matching.length > 0 ? matching : fallback;
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  useEffect(() => {
    if (!selectedKey && visible.length > 0) setSelectedKey(visible[0]._key);
  }, [visible, selectedKey]);
  const selected = visible.find((f) => f._key === selectedKey) || null;

  const startInstance = async (flowKey: string, subject: string, label: string) => {
    setBusy(flowKey);
    try {
      const res = await wizardApi.startInstance(flowKey, subject);
      void res;
      pushToast("ok", `Started ${label}${subject ? ` for ${subject}` : ""}.`);
      setScene("mission");
    } catch (err: any) {
      pushToast("err", `Start failed: ${err.message}`);
    } finally {
      setBusy(null);
    }
  };

  const tryQuickAction = async (label: string, subject: string, processHint: string) => {
    if (!flows) return;
    const match = flows.find((f) =>
      new RegExp(processHint, "i").test(`${f.display_name} ${f.description || ""} ${f.name || ""}`)
    );
    if (!match) {
      pushToast("err", `No published process matching "${processHint}". Build one in Studio.`);
      return;
    }
    await startInstance(match._key, subject, label);
  };

  return (
    <div className="hub-scene">
      <header className="hub-head">
        <div className="mc-hero-eyebrow"><Layers size={12} /> {spec.workbench}</div>
        <h2 className="mc-hero-title">{spec.title}</h2>
        <p className="hub-intro">{spec.intro}</p>
      </header>

      <section className="hub-commands">
        <div className="hub-section-label">{spec.title.split(" ")[0].toUpperCase()} WORKFLOW COMMANDS</div>
        <div className="hub-quick-grid">
          {spec.workflows.map((qa) => (
            <button
              key={qa.label}
              className="hub-quick-card"
              onClick={() => tryQuickAction(qa.label, qa.subject, qa.processHint)}
              disabled={!flows}
            >
              <div className="hub-quick-title"><Pulse size={12} /> {qa.label}</div>
              <div className="hub-quick-meta">Open workflow</div>
            </button>
          ))}
        </div>
      </section>

      <div className="hub-split">
        <section className="hub-queue">
          <div className="hub-section-label">{spec.title.split(" ")[0].toUpperCase()} QUEUE</div>
          {flows === null && <div className="hub-empty">Loading…</div>}
          {flows !== null && visible.length === 0 && (
            <div className="hub-empty">
              Nothing in the queue yet. Open the <button className="link-inline" onClick={() => setScene("studio")}>Process Studio</button> to publish a process.
            </div>
          )}
          <ul className="hub-queue-list">
            {visible.map((f) => (
              <li key={f._key}>
                <button
                  className={`hub-queue-row ${f._key === selectedKey ? "active" : ""}`}
                  onClick={() => setSelectedKey(f._key)}
                >
                  <Branch size={11} />
                  <span className="hub-queue-name">{f.display_name}</span>
                </button>
              </li>
            ))}
          </ul>
        </section>

        <section className="hub-selected">
          <div className="hub-section-label">SELECTED WORK</div>
          {!selected && <div className="hub-empty">Select a row on the left.</div>}
          {selected && (
            <div className="hub-flow-card">
              <div className="hub-flow-title"><Branch size={11} /> {selected.display_name}</div>
              {selected.description && <div className="hub-flow-desc">{selected.description.slice(0, 320)}</div>}
              <button
                className="btn btn-primary"
                disabled={busy === selected._key}
                onClick={() => startInstance(selected._key, "", selected.display_name)}
              >
                {busy === selected._key ? "Starting…" : "Start an instance"}
              </button>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}
