import { useEffect, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";
import api from "../api/client";

// ── Breadcrumb label cache (in-memory, survives re-renders) ────────────────
const labelCache = {};

// ── Segment label rules ────────────────────────────────────────────────────
const STATIC_LABELS = {
  "": "Home",
  dashboard: "Dashboard",
  devices: "Devices",
  users: "App Users",
  mqtt: "MQTT",
  commands: "Commands",
  logs: "Logs",
  equipment: "Equipment",
  notes: "Issues & Notes",
  mail: "Mail",
  crm: "CRM",
  comms: "Activity Log",
  customers: "Customers",
  orders: "Orders",
  products: "Products",
  quotations: "Quotations",
  new: "New",
  edit: "Edit",
  melodies: "Melodies",
  archetypes: "Archetypes",
  settings: "Settings",
  composer: "Composer",
  manufacturing: "Manufacturing",
  batch: "Batch",
  provision: "Provision Device",
  firmware: "Firmware",
  developer: "Developer",
  api: "API Reference",
  staff: "Staff",
};

// Maps a parent path segment to an async entity resolver
const ENTITY_RESOLVERS = {
  customers:  { apiPath: (id) => `/crm/customers/${id}`,   label: (d) => [d.name, d.surname].filter(Boolean).join(" ") || d.organization || null },
  products:   { apiPath: (id) => `/crm/products/${id}`,    label: (d) => d.name || null },
  quotations: { apiPath: (id) => `/crm/quotations/${id}`,  label: (d) => d.quotation_number || null },
  devices:    { apiPath: (id) => `/devices/${id}`,         label: (d) => d.name || d.device_id || null },
  orders:     { apiPath: (id) => `/crm/orders/${id}`,      label: (d) => d.order_number || null },
  melodies:   { apiPath: (id) => `/melodies/${id}`,        label: (d) => d.name || null },
  archetypes: { apiPath: (id) => `/builder/melodies/${id}`,label: (d) => d.name || null },
  users:      { apiPath: (id) => `/users/${id}`,           label: (d) => d.name || d.display_name || null },
  notes:      { apiPath: (id) => `/equipment/notes/${id}`, label: (d) => d.title || d.subject || null },
  staff:      { apiPath: (id) => `/staff/${id}`,           label: (d) => d.name || null },
};

// Fetch entity name for a dynamic ID segment
async function fetchLabel(fetchType, id) {
  const cacheKey = `${fetchType}:${id}`;
  if (labelCache[cacheKey]) return labelCache[cacheKey];

  const resolver = ENTITY_RESOLVERS[fetchType];
  if (!resolver) return id;

  try {
    const data = await api.get(resolver.apiPath(id));
    const label = resolver.label(data);
    if (label) {
      const short = String(label).length > 28 ? String(label).slice(0, 26) + "…" : String(label);
      labelCache[cacheKey] = short;
      return short;
    }
  } catch {
    // ignore — fall back to id
  }
  return id;
}

// Given a full path, return breadcrumb segments: [{ label, to }]
function parseSegments(pathname) {
  const parts = pathname.split("/").filter(Boolean);
  const segments = [{ label: "Home", to: "/" }];

  let i = 0;
  while (i < parts.length) {
    const part = parts[i];
    const built = "/" + parts.slice(0, i + 1).join("/");

    // Special multi-segment patterns
    if (part === "crm") {
      segments.push({ label: "CRM", to: "/crm/customers" });
      i++;
      continue;
    }
    if (part === "manufacturing" && parts[i + 1] === "batch" && parts[i + 2] === "new") {
      segments.push({ label: "Manufacturing", to: "/manufacturing" });
      segments.push({ label: "New Batch", to: built + "/batch/new" });
      i += 3;
      continue;
    }
    if (part === "manufacturing" && parts[i + 1] === "provision") {
      segments.push({ label: "Manufacturing", to: "/manufacturing" });
      segments.push({ label: "Provision Device", to: built + "/provision" });
      i += 2;
      continue;
    }
    if (part === "manufacturing" && parts[i + 1] === "devices") {
      segments.push({ label: "Manufacturing", to: "/manufacturing" });
      i++;
      continue;
    }
    // "devices" is handled by STATIC_LABELS below so the following ID segment
    // can detect prevPart === "devices" for entity resolution.
    // equipment/notes
    if (part === "equipment" && parts[i + 1] === "notes") {
      segments.push({ label: "Issues & Notes", to: "/equipment/notes" });
      i += 2;
      continue;
    }

    const staticLabel = STATIC_LABELS[part];
    if (staticLabel) {
      segments.push({ label: staticLabel, to: built });
    } else {
      // Dynamic ID segment — determine type from previous path segment
      const prevPart = parts[i - 1];
      const fetchType = ENTITY_RESOLVERS[prevPart] ? prevPart : null;

      // Use the raw id as placeholder — will be replaced asynchronously if fetchType is known
      segments.push({ label: part, to: built, dynamicId: part, fetchType });
    }
    i++;
  }

  return segments;
}

function Breadcrumb() {
  const location = useLocation();
  const [segments, setSegments] = useState(() => parseSegments(location.pathname));

  useEffect(() => {
    const parsed = parseSegments(location.pathname);
    setSegments(parsed);

    // Resolve any dynamic segments asynchronously
    const dynamics = parsed.filter((s) => s.fetchType && s.dynamicId);
    if (dynamics.length === 0) return;

    let cancelled = false;
    (async () => {
      const resolved = [...parsed];
      for (const seg of dynamics) {
        const label = await fetchLabel(seg.fetchType, seg.dynamicId);
        if (cancelled) return;
        const idx = resolved.findIndex((s) => s.dynamicId === seg.dynamicId && s.fetchType === seg.fetchType);
        if (idx !== -1) resolved[idx] = { ...resolved[idx], label };
      }
      if (!cancelled) setSegments([...resolved]);
    })();

    return () => { cancelled = true; };
  }, [location.pathname]);

  // Don't show breadcrumb for root
  if (segments.length <= 1) return null;

  // Remove "Home" from display if not on root
  const display = segments.slice(1);

  return (
    <nav aria-label="Breadcrumb" style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14 }}>
      <span style={{ color: "var(--border-primary)", userSelect: "none", margin: "0px 18px 0px 10px", fontSize: 15 }}>|</span>

      {display.map((seg, i) => (
        <span key={i} style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {i > 0 && (
            <span style={{ color: "var(--text-muted)", userSelect: "none", fontSize: 11 }}>›</span>
          )}
          {i === display.length - 1 ? (
            <span style={{ color: "var(--text-heading)", fontWeight: 600 }}>{seg.label}</span>
          ) : (
            <Link
              to={seg.to}
              style={{ color: "var(--text-secondary)", textDecoration: "none" }}
              onMouseEnter={(e) => (e.currentTarget.style.color = "var(--text-heading)")}
              onMouseLeave={(e) => (e.currentTarget.style.color = "var(--text-secondary)")}
            >
              {seg.label}
            </Link>
          )}
        </span>
      ))}
    </nav>
  );
}

export default function Header() {
  const { user, logout } = useAuth();

  return (
    <header
      className="px-6 flex items-center justify-between border-b flex-shrink-0"
      style={{
        backgroundColor: "var(--bg-header)",
        borderColor: "var(--border-primary)",
        height: "54px",
      }}
    >
      <div className="flex items-center gap-5">
        <img
          src="/horizontal-logo-dark-console.png"
          alt="BellSystems"
          style={{ height: "22px", width: "auto", objectFit: "contain" }}
        />
        <Breadcrumb />
      </div>

      <div className="flex items-center gap-5">
        <span className="text-sm" style={{ color: "var(--text-secondary)" }}>
          {user?.name}
          <span
            className="ml-2 px-2 py-0.5 text-xs rounded-full"
            style={{
              backgroundColor: "var(--badge-blue-bg)",
              color: "var(--badge-blue-text)",
            }}
          >
            {user?.role}
          </span>
        </span>
        <button
          onClick={logout}
          className="text-sm transition-colors"
          style={{ color: "var(--danger)" }}
          onMouseEnter={(e) => (e.target.style.color = "var(--danger-hover)")}
          onMouseLeave={(e) => (e.target.style.color = "var(--danger)")}
        >
          Sign out
        </button>
      </div>
    </header>
  );
}
