import type { MouseEvent } from "react";
import type { PatientSummary } from "../../api/types";
import { dayLabel, whenLabel } from "../../logic/format";
import { attentionLabel, sharedByLine, tileValues } from "../../logic/patients";
import { checkInPill, patientStatePill } from "../../logic/pills";
import { personLine } from "../../logic/today";
import { Icon, StatusPill } from "../kit";
import { Link, navigate } from "../router";
import { attentionPill, DoseBar, PatientAvatar, StatePill } from "./bits";

const heads = ["Patient", "Sharing", "Medicines", "Doses this week", "Last check-in", "Last activity"];
const cell = "border-b border-hairline px-2 py-3 align-middle";
const quiet = (text: string) => <span className="text-[13px] text-subtle">{text}</span>;

/** Desktop: one row per patient. The name is the link; a click anywhere else on the row opens it too. */
export function PatientTable({ patients }: { patients: PatientSummary[] }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full min-w-[820px] border-separate border-spacing-0 text-left text-[14px] text-ink">
        <thead>
          <tr>
            {heads.map((h, i) => (
              <th key={h} scope="col" className={`h-10 border-b border-hairline px-2 text-[12.5px] font-normal whitespace-nowrap text-muted ${i === 0 ? "pl-3" : ""}`}>
                {h}
              </th>
            ))}
            <th scope="col" className="w-8 border-b border-hairline">
              <span className="sr-only">Open</span>
            </th>
          </tr>
        </thead>
        <tbody>
          {patients.map((p) => (
            <Row key={p.id} p={p} />
          ))}
        </tbody>
      </table>
    </div>
  );
}

function Row({ p }: { p: PatientSummary }) {
  const values = tileValues(p);
  const attention = attentionLabel(p);
  const look = attentionPill(p);
  const to = `/app/patients/${p.id}`;
  const open = (e: MouseEvent) => {
    if ((e.target as HTMLElement).closest("a, button") || window.getSelection()?.toString()) return;
    navigate(to);
  };
  const doses = p.sharing?.status === "connected" && p.sharing.scopes.includes("doses") && p.doses && p.doses.expected > 0 ? p.doses : null;
  const last = values && values.lastCheckIn.value !== "Paused" ? p.lastCheckIn : null;
  return (
    <tr onClick={open} className="group cursor-pointer transition-colors hover:bg-tile [&:last-child>td]:border-b-0">
      <td className={`${cell} pl-3`}>
        <div className="flex min-w-0 items-center gap-3">
          <PatientAvatar name={p.name} />
          <span className="flex min-w-0 flex-col items-start">
            <Link to={to} className="truncate rounded-sm font-medium text-ink no-underline outline-none hover:underline focus-visible:shadow-[0_0_0_2px_var(--color-brand)]">
              {p.name}
            </Link>
            <span className="truncate text-[12.5px] text-muted">{personLine(p) || (p.kind === "clinic_added" ? "Clinic patient" : "From MARMAR Health")}</span>
            {attention && look && (
              <StatusPill tone={look.tone} icon={look.icon} size="sm" className="mt-1.5">
                {attention}
              </StatusPill>
            )}
          </span>
        </div>
      </td>
      <td className={cell}>
        <span className="flex flex-col items-start gap-1">
          <StatePill pill={patientStatePill(p)} />
          {p.sharing && <span className="max-w-44 truncate text-[12px] text-subtle">{sharedByLine(p.sharing)}</span>}
        </span>
      </td>
      {values ? (
        <>
          <td className={`${cell} whitespace-nowrap`}>
            {/^\d+$/.test(values.medicines.value) ? <span className="font-medium tabular-nums">{values.medicines.value}</span> : quiet(values.medicines.value)}
          </td>
          <td className={`${cell} whitespace-nowrap`} title={values.doses.note}>
            {doses ? (
              <span className="flex w-28 flex-col gap-1.5">
                <span className="font-medium tabular-nums">
                  {doses.taken} <span className="font-normal text-subtle">of {doses.expected}</span>
                </span>
                <DoseBar taken={doses.taken} expected={doses.expected} />
              </span>
            ) : (
              quiet(values.doses.value)
            )}
          </td>
          <td className={`${cell} whitespace-nowrap`}>
            {last ? (
              <span className="flex flex-col items-start gap-1">
                {last.kind === "yasmar_call" && last.status ? (
                  <StatePill pill={checkInPill(last.status)} />
                ) : (
                  <StatusPill tone="grey" icon={last.kind === "daily" ? "calendar-check-fill" : "phone-fill"} size="sm">
                    {last.kind === "daily" ? "Daily check-in" : "Yasmar call"}
                  </StatusPill>
                )}
                <span className="text-[12px] text-subtle">
                  {last.kind === "yasmar_call" && last.status ? "Yasmar call · " : ""}
                  {dayLabel(last.at)}
                </span>
              </span>
            ) : (
              quiet(values.lastCheckIn.value)
            )}
          </td>
        </>
      ) : (
        <td colSpan={3} className={`${cell} text-[13px] text-muted`}>
          {p.sharing?.status === "stopped"
            ? `Sharing stopped ${whenLabel(p.sharing.changedAt)}. You keep the checks and check-ins you saved.`
            : `Invite ${p.name.split(" ")[0]} to MARMAR Health to see medicines, doses and check-ins from the app.`}
        </td>
      )}
      <td className={`${cell} font-mono text-[12px] whitespace-nowrap text-subtle`}>{whenLabel(p.lastActivityAt)}</td>
      <td className={`${cell} pr-3 text-subtle`}>
        <Icon name="arrow-right-s-line" size={18} className="opacity-50 transition-opacity group-hover:opacity-100" />
      </td>
    </tr>
  );
}
