"use client";
import { createContext, useContext, useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { getOrganizationForPath } from "@/app/_lib/orgSession";
import { getCurrentUser, getDoctorProfile } from "./_api";
import { DoctorProfile, EMPTY_DOCTOR_PROFILE } from "./_types";

// The HMS module lives at this fixed base path in the sidebar's Project
// record (see HMS_README.md) — the sidebar stores the organization it was
// clicked with under this exact key in sessionStorage, regardless of which
// HMS sub-page the person is currently on.
const HMS_BASE_PATH = "/private/hms";

type HmsContextValue = {
  organizationId: number;
  userId: number;
  doctor: DoctorProfile;
  setDoctor: (d: DoctorProfile) => void;
  ready: boolean;
};

const HmsContext = createContext<HmsContextValue | null>(null);

export function useHms() {
  const ctx = useContext(HmsContext);
  if (!ctx) throw new Error("useHms must be used within the HMS layout");
  return ctx;
}

const NAV_ITEMS = [
  { href: "/private/hms/panel", label: "Doctor Panel" },
  { href: "/private/hms/registration", label: "Registration" },
  { href: "/private/hms/setup", label: "Doctor Setup" },
];

export default function HmsLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const organizationId = Number(getOrganizationForPath(HMS_BASE_PATH) || 1);
  const [userId, setUserId] = useState<number | null>(null);
  const [doctor, setDoctor] = useState<DoctorProfile>(EMPTY_DOCTOR_PROFILE);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const me = await getCurrentUser();
      if (cancelled) return;
      setUserId(me.id);
      const profile = await getDoctorProfile(organizationId, me.id);
      if (cancelled) return;
      setDoctor(profile || { ...EMPTY_DOCTOR_PROFILE, name: `${me.first_name} ${me.last_name}`.trim(), email: me.email });
      setReady(true);
    })();
    return () => { cancelled = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [organizationId]);

  return (
    <div className="card">
      <div className="card-header">
        <ul className="nav nav-tabs card-header-tabs">
          {NAV_ITEMS.map((item) => (
            <li className="nav-item" key={item.href}>
              <Link href={item.href} className={"nav-link" + (pathname === item.href ? " active" : "")}>
                {item.label}
              </Link>
            </li>
          ))}
        </ul>
      </div>
      <div className="card-body">
        {!ready || userId === null ? (
          <p className="text-muted small mb-0">Loading HMS…</p>
        ) : (
          <HmsContext.Provider value={{ organizationId, userId, doctor, setDoctor, ready }}>
            {children}
          </HmsContext.Provider>
        )}
      </div>
    </div>
  );
}
