"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Trophy } from "lucide-react";
import { api } from "@/lib/api";

export default function LoginPage() {
  const router = useRouter();
  const [user, setUser] = useState("");
  const [pass, setPass] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setErr("");
    const ok = await api.login(user.trim(), pass);
    setBusy(false);
    if (ok) router.replace("/");
    else setErr("نام کاربری یا رمز اشتباه است");
  }

  return (
    <div className="min-h-screen grid place-items-center p-6">
      <form
        onSubmit={submit}
        className="card w-full max-w-sm p-7 flex flex-col gap-4"
      >
        <div className="flex flex-col items-center gap-2 mb-2">
          <Trophy className="text-[var(--gold)]" size={38} />
          <h1 className="text-xl font-bold text-[var(--gold)]">
            پنل مدیریت حکم‌شو
          </h1>
        </div>
        <label className="text-sm">
          نام کاربری
          <input
            className="inp mt-1"
            value={user}
            onChange={(e) => setUser(e.target.value)}
            autoFocus
          />
        </label>
        <label className="text-sm">
          رمز عبور
          <input
            className="inp mt-1"
            type="password"
            value={pass}
            onChange={(e) => setPass(e.target.value)}
          />
        </label>
        {err && <p className="text-red-400 text-sm">{err}</p>}
        <button className="btn btn-gold mt-2" disabled={busy}>
          {busy ? "…" : "ورود"}
        </button>
      </form>
    </div>
  );
}
