"use client";

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

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

  const selected = permissions.split(",").map((i) => i.trim()).filter(Boolean);
  const quickAdd = (value: string) => {
    setPermissions((prev) =>
      prev
        .split(",")
        .map((v) => v.trim())
        .filter(Boolean)
        .concat(selected.includes(value) ? [] : [value])
        .join(", ")
    );
  };

  const submit = async () => {
    if (disabled || !code) return;
    setLoading(true);
    try {
      await onSubmit({ code, permissionCodes: selected });
      setCode("");
      setPermissions("");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="vstack gap-2">
      <input
        className="form-control"
        value={code}
        onChange={(e) => setCode(e.target.value)}
        placeholder={t("roleCode", locale)}
        disabled={disabled}
      />
      <input
        className="form-control"
        value={permissions}
        onChange={(e) => setPermissions(e.target.value)}
        placeholder={t("permissions", locale)}
        disabled={disabled}
      />
      <div className="d-flex flex-wrap gap-2">
        {permissionCatalog.map((permission) => (
          <button
            key={permission}
            type="button"
            className="btn btn-sm btn-outline-secondary"
            onClick={() => quickAdd(permission)}
            disabled={disabled}
          >
            {permission}
          </button>
        ))}
      </div>
      <button className="btn btn-outline-primary" disabled={disabled || loading} onClick={submit} type="button">
        {loading ? t("submitting", locale) : t("save", locale)}
      </button>
    </div>
  );
}
