import { useState } from "react";
import { clinicianApi } from "../../api/client";
import type { ClinicianSession } from "../../api/types";
import { Button, Checkbox, FieldError } from "../kit";
import { errorText } from "../ui";
import { StepTitle } from "./AuthFrame";

/** ACC-10: real patients need the clinician terms and the data processing terms, accepted once here. */
export function Terms({ onDone }: { onDone: (s: ClinicianSession) => void }) {
  const [agreed, setAgreed] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const accept = async () => {
    setBusy(true);
    setError("");
    try {
      onDone(await clinicianApi.acceptTerms());
    } catch (e) {
      setError(errorText(e));
    } finally {
      setBusy(false);
    }
  };
  const link = "font-medium text-ink underline decoration-line underline-offset-4 hover:decoration-ink";
  return (
    <div className="flex flex-col gap-5">
      <StepTitle icon="file-text-line" iconClass="text-blue-icon" title="Accept the clinician terms">
        Before you work with real patients, accept the{" "}
        <a href="/terms/clinician" target="_blank" rel="noreferrer" className={link}>
          clinician terms
        </a>{" "}
        and the{" "}
        <a href="/terms/data-processing" target="_blank" rel="noreferrer" className={link}>
          data processing terms
        </a>{" "}
        for the records you add. Context shows information and where it came from. You make every decision.
      </StepTitle>
      <Checkbox checked={agreed} onChange={(e) => setAgreed(e.target.checked)}>
        I accept both.
      </Checkbox>
      {error && <FieldError>{error}</FieldError>}
      <Button variant="primary" size="lg" className="w-full" disabled={!agreed || busy} onClick={() => void accept()}>
        {busy ? "Saving…" : "Accept and continue"}
      </Button>
    </div>
  );
}
