"use client";

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

export default function RoleCreateForm({
  disabled,
  onSubmit
}: {
  disabled: boolean;
  onSubmit: (payload: { code: string; name: string; permissionCodes: string[] }) => Promise<void>;
}) {
  const locale = useLocaleStore((s) => s.locale);
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [permissions, setPermissions] = useState("");
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    if (disabled || !code || !name) return;
    setLoading(true);
    try {
      await onSubmit({
        code,
        name,
        permissionCodes: permissions
          .split(",")
          .map((it) => it.trim())
          .filter(Boolean)
      });
      setCode("");
      setName("");
      setPermissions("");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="vstack gap-2">
      <input
        className="form-control"
        value={code}
        onChange={(e) => setCode(e.target.value)}
        placeholder={t("code", locale)}
        disabled={disabled}
      />
      <input
        className="form-control"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder={t("name", locale)}
        disabled={disabled}
      />
      <input
        className="form-control"
        value={permissions}
        onChange={(e) => setPermissions(e.target.value)}
        placeholder="permission codes (comma separated)"
        disabled={disabled}
      />
      <button className="btn btn-primary" disabled={disabled || loading} onClick={submit} type="button">
        {loading ? t("submitting", locale) : t("create", locale)}
      </button>
    </div>
  );
}
