"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { adminLoginAction } from "@/server/actions/admin-auth";

export function AdminLoginForm({ next }: { next: string }) {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [error, setError] = useState("");
  const [show, setShow] = useState(false);

  function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    setError("");
    start(async () => {
      const res = await adminLoginAction({ phone: String(fd.get("phone") ?? ""), password: String(fd.get("password") ?? "") });
      if (!res.ok) return setError(res.error);
      router.replace(next);
      router.refresh();
    });
  }

  return (
    <form onSubmit={submit} className="space-y-4" noValidate>
      <label className="block">
        <span className="label">شماره موبایل</span>
        <input name="phone" className="field" inputMode="tel" autoComplete="username" dir="ltr" placeholder="09xxxxxxxxx" maxLength={14} required />
      </label>
      <label className="block">
        <span className="label flex items-center justify-between">
          رمز عبور
          <button type="button" className="text-[11px] font-normal text-muted underline" onClick={() => setShow((s) => !s)}>{show ? "پنهان" : "نمایش"}</button>
        </span>
        <input name="password" type={show ? "text" : "password"} className="field" autoComplete="current-password" dir="ltr" maxLength={128} required />
      </label>
      {error && <p role="alert" className="rounded-xl bg-mist px-4 py-3 text-sm">⚠ {error}</p>}
      <button className="btn-primary w-full" disabled={pending}>{pending ? "در حال ورود…" : "ورود به پنل"}</button>
    </form>
  );
}
