"use client";

import { useState, useTransition } from "react";
import { changeOwnPasswordAction } from "@/server/admin/team";

export function ChangePasswordForm() {
  const [pending, start] = useTransition();
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    const fd = new FormData(form);
    if (fd.get("next") !== fd.get("repeat")) return setMsg({ ok: false, text: "رمز جدید و تکرار آن یکسان نیستند" });
    start(async () => {
      const res = await changeOwnPasswordAction({ current: String(fd.get("current")), next: String(fd.get("next")) });
      setMsg(res.ok ? { ok: true, text: "رمز عوض شد" } : { ok: false, text: res.error });
      if (res.ok) form.reset();
    });
  }
  return (
    <form onSubmit={submit} className="max-w-sm space-y-3 rounded-2xl bg-paper p-5">
      <label className="block"><span className="label">رمز فعلی</span><input name="current" type="password" className="field h-10" dir="ltr" autoComplete="current-password" required /></label>
      <label className="block"><span className="label">رمز جدید</span><input name="next" type="password" className="field h-10" dir="ltr" autoComplete="new-password" required /></label>
      <label className="block"><span className="label">تکرار رمز جدید</span><input name="repeat" type="password" className="field h-10" dir="ltr" autoComplete="new-password" required /></label>
      <p className="text-[11px] text-muted">حداقل ۸ کاراکتر، شامل حرف و عدد</p>
      {msg && <p role="status" className="text-sm">{msg.ok ? "✓" : "⚠"} {msg.text}</p>}
      <button className="btn-primary h-10 w-full" disabled={pending}>{pending ? "…" : "تغییر رمز"}</button>
    </form>
  );
}
