import { useEffect, useRef, useState } from "react";
import { habitRequest, type TodayHabit } from "../lib/dashboard";
import { Button } from "./design-system/primitives";

export function DeleteHabit({
  habit,
  onClose,
  onDeleted,
}: {
  habit: TodayHabit;
  onClose: () => void;
  onDeleted: () => void;
}) {
  const dialog = useRef<HTMLDialogElement>(null);
  const saving = useRef(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  useEffect(() => {
    const previous = document.activeElement as HTMLElement | null;
    dialog.current?.showModal();
    return () => previous?.focus();
  }, []);
  async function remove() {
    if (saving.current) return;
    saving.current = true;
    setBusy(true);
    setError("");
    try {
      await habitRequest(`/habits/${habit.habitId}`, { method: "DELETE" });
      onDeleted();
    } catch (error) {
      setError(
        error instanceof Error ? error.message : "Could not delete your habit.",
      );
      saving.current = false;
      setBusy(false);
    }
  }
  return (
    <dialog
      ref={dialog}
      className="home-create home-delete"
      aria-labelledby="delete-title"
      aria-describedby="delete-description"
      onCancel={(event) => {
        event.preventDefault();
        if (!saving.current) onClose();
      }}
    >
      <p className="ds-eyebrow">MAKE A LITTLE ROOM</p>
      <h2 id="delete-title">
        Delete this <em>habit?</em>
      </h2>
      <p id="delete-description" className="ds-muted">
        <strong>{habit.name}</strong> will leave your dashboard and stop future
        check-ins. Your recorded history is kept, not permanently erased.
      </p>
      {error && (
        <p className="home-error" role="alert">
          {error}
        </p>
      )}
      <div className="home-form-actions">
        <Button variant="secondary" disabled={busy} onClick={onClose} autoFocus>
          Keep habit
        </Button>
        <Button disabled={busy} onClick={() => void remove()}>
          {busy ? "Deleting…" : "Delete habit"}
        </Button>
      </div>
    </dialog>
  );
}
