"use client";

import { useState } from "react";
import { useLocaleStore } from "@/store/uiStore";
import { t } from "@/lib/locale";

export default function UserRoleUpdateForm({
  disabled,
  onSubmit
}: {
  disabled: boolean;
  onSubmit: (payload: { username: string; roleCodes: string[] }) => Promise<void>;
}) {
  const locale = useLocaleStore((s) => s.locale);
  const [username, setUsername] = useState("");
  const [roles, setRoles] = useState("");
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    if (disabled || !username) return;
    setLoading(true);
    try {
      await onSubmit({
        username,
        roleCodes: roles
          .split(",")
          .map((role) => role.trim())
          .filter(Boolean)
      });
      setUsername("");
      setRoles("");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="vstack gap-2">
      <input
        className="form-control"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder={t("username", locale)}
        disabled={disabled}
      />
      <input
        className="form-control"
        value={roles}
        onChange={(e) => setRoles(e.target.value)}
        placeholder="Role codes (comma separated)"
        disabled={disabled}
      />
      <button className="btn btn-outline-primary" onClick={submit} disabled={disabled || loading} type="button">
        {loading ? t("submitting", locale) : t("update", locale)}
      </button>
    </div>
  );
}
