import { clinicianApi } from "../../api/client";
import type { ActivityEvent, PatientDetail } from "../../api/types";
import { whenLabel } from "../../logic/format";
import { cn } from "../kit";
import { ErrorNote, Spinner, useLoad } from "../ui";

// You and colleagues in green, the patient's side in purple, MARMAR in grey.
const dot: Record<ActivityEvent["actorKind"], string> = {
  clinician: "bg-green-icon",
  patient: "bg-purple-icon",
  carer: "bg-purple-icon",
  system: "bg-subtle",
};

/** INV-15, SEC-3: who did what for this patient, on both sides, newest first, as a quiet timeline. */
export function ActivityList({ patient }: { patient: PatientDetail }) {
  const activity = useLoad(() => clinicianApi.activity(patient.id), [patient.id]);
  const events = activity.data?.events ?? [];
  return (
    <>
      {activity.loading && !activity.data && <Spinner />}
      <ErrorNote error={activity.error} onRetry={() => activity.reload()} />
      <ol className="m-0 flex list-none flex-col p-0">
        {events.map((e, i) => (
          <li key={e.id} className="flex gap-3 py-2">
            <span aria-hidden="true" className="flex w-2 shrink-0 flex-col items-center">
              <span className={cn("mt-1.5 size-2 rounded-full", dot[e.actorKind])} />
              {i < events.length - 1 && <span className="-mb-4 mt-1 w-px flex-1 bg-hairline" />}
            </span>
            <span className="flex min-w-0 flex-col gap-0.5">
              <span className="text-[13.5px] leading-[19px] font-medium text-ink">{e.action}</span>
              <span className="text-[12px] leading-[17px] text-muted">
                {e.actor} ·{" "}
                <time dateTime={e.at} className="font-mono text-[11.5px] text-subtle">
                  {whenLabel(e.at)}
                </time>
              </span>
            </span>
          </li>
        ))}
      </ol>
      {activity.data && !events.length && <p className="m-0 text-[13px] text-muted">Nothing yet.</p>}
    </>
  );
}
