const RoleModal = ({
  isOpen,
  onClose,
  role,
  allPermissions,
  onSubmit,
  loading,
}) => {
  const [formData, setFormData] = React.useState({
    name: "",
    description: "",
    permission_ids: [],
  });

  React.useEffect(() => {
    if (role) {
      // Edit Mode
      setFormData({
        name: role.name,
        description: role.description || "",
        permission_ids: role.permissions
          ? role.permissions.map((p) => p.id)
          : [],
      });
    } else {
      // Create Mode
      setFormData({ name: "", description: "", permission_ids: [] });
    }
  }, [role, isOpen]);

  const handlePermissionToggle = (permId) => {
    setFormData((prev) => {
      const exists = prev.permission_ids.includes(permId);
      if (exists) {
        return {
          ...prev,
          permission_ids: prev.permission_ids.filter((id) => id !== permId),
        };
      } else {
        return { ...prev, permission_ids: [...prev.permission_ids, permId] };
      }
    });
  };

  if (!isOpen) return null;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={role ? "✏️ Edit Role" : "➕ Buat Role Baru"}
      size="large"
    >
      <form
        onSubmit={(e) => {
          e.preventDefault();
          onSubmit(formData);
        }}
        className="space-y-4"
      >
        <div>
          <label className="block font-semibold mb-2 text-slate-300">
            Nama Role
          </label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            disabled={role && (role.name === "admin" || role.name === "user")}
            className="w-full px-4 py-3 bg-slate-700 border-2 border-slate-600 rounded-xl text-white focus:border-blue-500 focus:outline-none"
            required
          />
        </div>

        <div>
          <label className="block font-semibold mb-2 text-slate-300">
            Deskripsi
          </label>
          <textarea
            value={formData.description}
            onChange={(e) =>
              setFormData({ ...formData, description: e.target.value })
            }
            className="w-full px-4 py-3 bg-slate-700 border-2 border-slate-600 rounded-xl text-white focus:border-blue-500 focus:outline-none"
            rows="2"
          />
        </div>

        <div>
          <label className="block font-semibold mb-2 text-slate-300">
            Permissions (Hak Akses)
          </label>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-h-60 overflow-y-auto bg-slate-900/50 p-4 rounded-xl border border-slate-700">
            {allPermissions.map((perm) => (
              <label
                key={perm.id}
                className="flex items-start gap-2 cursor-pointer p-2 hover:bg-slate-700 rounded transition"
              >
                <input
                  type="checkbox"
                  className="mt-1"
                  checked={formData.permission_ids.includes(perm.id)}
                  onChange={() => handlePermissionToggle(perm.id)}
                />
                <div>
                  <div className="text-sm font-semibold text-white">
                    {perm.name}
                  </div>
                  <div className="text-xs text-slate-400">{perm.slug}</div>
                </div>
              </label>
            ))}
          </div>
        </div>

        <button
          type="submit"
          disabled={loading}
          className="w-full px-4 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl hover:from-blue-700 hover:to-blue-800 transition font-semibold shadow-lg"
        >
          {loading ? "Menyimpan..." : "Simpan Role"}
        </button>
      </form>
    </Modal>
  );
};
window.RoleModal = RoleModal;
