import { navigate } from "./router";
import { displayName, useClinician } from "./session";
import { ClinicSection } from "./settings/Clinic";
import { HoursSection } from "./settings/Hours";
import { ProfileSection } from "./settings/Profile";
import { NotificationsSection, SecuritySection } from "./settings/Security";
import Shell from "./Shell";
import { UnderlineTabs } from "./kit";
import { useToast } from "./ui";

const sections = [
  { id: "profile", label: "Profile", to: "/app/settings" },
  { id: "clinic", label: "Clinic", to: "/app/settings/clinic" },
  { id: "hours", label: "Calling hours", to: "/app/settings/hours" },
  { id: "security", label: "Security", to: "/app/settings/security" },
  { id: "notifications", label: "Notifications", to: "/app/settings/notifications" },
] as const;

/** ACC-7 to ACC-9, YCI-5 and NTF-2: profile, clinic, calling hours, security and notifications, a tab each with its own address. */
export default function Settings({ section }: { section?: string }) {
  const { me, clinic } = useClinician();
  const toast = useToast();
  const current = sections.find((s) => s.id === section) ?? sections[0];
  if (section && section !== current.id) queueMicrotask(() => navigate("/app/settings", { replace: true }));
  const noHours = !clinic.openingHours.length || !clinic.alertWatchHours.length;

  return (
    <Shell crumbs={[{ label: "Settings", to: "/app/settings" }, { label: current.label }]} active="settings">
      <div className="mx-auto flex w-full max-w-[920px] flex-col gap-5 pt-2 pb-12 md:pt-6">
        <header className="flex min-w-0 flex-col gap-0.5">
          <h1 className="m-0 text-[26px] leading-8 font-semibold tracking-[-0.02em] text-ink md:text-[30px] md:leading-9">Settings</h1>
          <span className="text-[13.5px] text-muted">
            {displayName(me)} · {clinic.name}
          </span>
        </header>
        <UnderlineTabs
          label="Settings sections"
          active={current.id}
          items={sections.map((s) => ({ ...s, ...(s.id === "hours" && noHours && { dot: { tone: "amber" as const, label: "Hours not set" } }) }))}
        />
        <div key={current.id} className="flex flex-col gap-4">
          {current.id === "profile" && <ProfileSection onSaved={toast.show} />}
          {current.id === "clinic" && <ClinicSection onSaved={toast.show} />}
          {current.id === "hours" && <HoursSection onSaved={toast.show} />}
          {current.id === "security" && <SecuritySection onSaved={toast.show} />}
          {current.id === "notifications" && <NotificationsSection onSaved={toast.show} />}
        </div>
      </div>
      {toast.node}
    </Shell>
  );
}
