import { useState } from "react";
import { registerAdmin } from "../api/index";

const ROLES = [
  { value: "Рабочий", label: "Рабочий" },
  { value: "Админ", label: "Администратор" },
];

export default function AdminStaff() {
  const [form, setForm] = useState({
    username: "",
    password: "",
    first_name: "",
    last_name: "",
    phone: "",
    role: "Рабочий",
  });
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState(null);

  const handleChange = (field) => (e) =>
    setForm({ ...form, [field]: e.target.value });

  const handleSubmit = async () => {
    // валидация
    if (!form.username.trim()) {
      setMessage({ type: "error", text: "Введите логин" });
      return;
    }
    if (form.password.length < 8) {
      setMessage({ type: "error", text: "Пароль минимум 8 символов" });
      return;
    }
    if (!form.first_name.trim() || !form.last_name.trim()) {
      setMessage({ type: "error", text: "Введите имя и фамилию" });
      return;
    }

    setBusy(true);
    setMessage(null);
    try {
      await registerAdmin(form);
      setMessage({ type: "success", text: "Сотрудник зарегистрирован" });
      // очистить форму
      setForm({
        username: "",
        password: "",
        first_name: "",
        last_name: "",
        phone: "",
        role: "Рабочий",
      });
    } catch (err) {
      setMessage({
        type: "error",
        text: err.response?.data?.error || "Не удалось зарегистрировать",
      });
    } finally {
      setBusy(false);
    }
  };

  const inputClass =
    "bg-white/5 border border-white/10 rounded px-3 py-2 text-white placeholder-white/40 focus:border-gold focus:outline-none";

  return (
    <div className="max-w-md">
      <h2 className="text-xl font-medium text-white mb-4">
        Регистрация сотрудника
      </h2>

      <div className="flex flex-col gap-3">
        <input
          className={inputClass}
          placeholder="Логин"
          value={form.username}
          onChange={handleChange("username")}
        />
        <input
          type="password"
          className={inputClass}
          placeholder="Пароль (минимум 8 символов)"
          value={form.password}
          onChange={handleChange("password")}
        />
        <input
          className={inputClass}
          placeholder="Имя"
          value={form.first_name}
          onChange={handleChange("first_name")}
        />
        <input
          className={inputClass}
          placeholder="Фамилия"
          value={form.last_name}
          onChange={handleChange("last_name")}
        />
        <input
          className={inputClass}
          placeholder="Телефон (необязательно)"
          value={form.phone}
          onChange={handleChange("phone")}
        />

        {/* роль */}
        <select
          className={inputClass}
          value={form.role}
          onChange={handleChange("role")}
        >
          {ROLES.map((r) => (
            <option key={r.value} value={r.value}>
              {r.label}
            </option>
          ))}
        </select>

        {/* сообщение */}
        {message && (
          <p
            className={`text-sm ${message.type === "success" ? "text-green-400" : "text-red-400"
              }`}
          >
            {message.text}
          </p>
        )}

        <button
          onClick={handleSubmit}
          disabled={busy}
          className="bg-gold text-black px-6 py-2 rounded font-medium uppercase text-sm disabled:opacity-50"
        >
          {busy ? "Регистрация..." : "Зарегистрировать"}
        </button>
      </div>
    </div>
  );
}
