"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import type { ActionResult } from "@/lib/actions/result";

export type Msg = { ok: boolean; text: string } | null;

export function useRun() {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [msg, setMsg] = useState<Msg>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const run = (fn: () => Promise<ActionResult<unknown> | void>, onOk?: () => void) => {
    setMsg(null); setErrors({});
    start(async () => {
      const r = await fn();
      if (r && !r.ok) { setErrors(r.fieldErrors ?? {}); setMsg({ ok: false, text: r.error }); }
      else if (r) { setMsg({ ok: true, text: r.message ?? "Done" }); onOk?.(); router.refresh(); }
    });
  };
  return { pending, msg, errors, run };
}

export const StatusLine = ({ msg }: { msg: Msg }) => (
  <p role="status" aria-live="polite" className={msg ? (msg.ok ? "text-sm text-success" : "text-sm text-danger") : "sr-only"}>{msg?.text}</p>
);
